优化这段代码imgfilename1='C:\Users\86182\Desktop\tif\QB2013.dat'; imgfilename2='C:\Users\86182\Desktop\tif\SV2018.dat'; fid1=fopen(imgfilename1,'r'); data=multibandread(imgfilename1,[1989,2126,4],'int16',0,'bsq','ieee-le');%lines,samples,bands data=double(data); B1=data(:,:,1); G1=data(:,:,2); R1=data(:,:,3); C1=data(:,:,4); data=cat(4,B1,C1,R1,G1); %数值转换为0-255的整型用于显示 data_unit8=data; for k=1:4 min_val=min(data(:,:,k)); max_val=max(data(:,:,k)); for i=1:1989 for j=1:2126 data_unit8(i,j,k)=uint8((data_unit8(i,j,k)-min_val)/(max_val-min_val)*255); end end end data_show=data; for k=1:4 min_val=min(data(:,:,k)); max_val=max(data(:,:,k)); for i=1:1989 for j=1:2126 data_show(i,j,k)=uint8((data_show(i,j,k)-min_val)/(max_val-min_val)*255); end end end fid2=fopen(imgfilename2,'r'); data2=multibandread(imgfilename2,[1989,2126,4],'int16',0,'bsq','ieee-le');%lines,samples,bands data2=double(data2); B2=data2(:,:,1); G2=data2(:,:,2); R2=data2(:,:,3); C2=data2(:,:,4); data2=cat(4,B2,C2,R2,G2); %数值转换为0-255的整型用于显示 data_unit8=data2; for k=1:4 min_val=min(data2(:,:,k)); max_val=max(data2(:,:,k)); for i=1:1989 for j=1:2126 data_unit8(i,j,k)=uint8((data_unit8(i,j,k)-min_val)/(max_val-min_val)*255); end end end data_show=data2; for k=1:4 min_val=min(data2(:,:,k)); max_val=max(data2(:,:,k)); for i=1:1989 for j=1:2126 data_show(i,j,k)=uint8((data_show(i,j,k)-min_val)/(max_val-min_val)*255); end end end
时间: 2024-03-07 19:48:36 浏览: 54
用户管理-c语言 用指针作为函数返回值详解
这段代码可以进行如下优化:
1. 将重复的代码封装成函数,避免代码重复。
2. 使用矩阵运算优化循环部分的代码,避免循环次数过多。
3. 使用适当的变量名和注释,提高代码可读性。
下面是优化后的代码:
```
function data = read_data(filename)
% 读取数据
fid = fopen(filename, 'r');
data = multibandread(filename, [1989, 2126, 4], 'int16', 0, 'bsq', 'ieee-le');
data = double(data);
% 将数据转换为0-255的整型用于显示
data_unit8 = uint8(data);
for k = 1:4
min_val = min(data(:, :, k), [], 'all');
max_val = max(data(:, :, k), [], 'all');
data_unit8(:, :, k) = uint8((data_unit8(:, :, k) - min_val) / (max_val - min_val) * 255);
end
% 返回处理后的数据
data = data_unit8;
end
% 读取第一组数据
imgfilename1 = 'C:\Users\86182\Desktop\tif\QB2013.dat';
data1 = read_data(imgfilename1);
% 读取第二组数据
imgfilename2 = 'C:\Users\86182\Desktop\tif\SV2018.dat';
data2 = read_data(imgfilename2);
```
阅读全文