How Can i speed up "for" loop ?
49 次查看(过去 30 天)
显示 更早的评论
Hello to everyone, I need to speed up my for loop. I use this loop for filling a vector with a temperature profile (that changes over time). I don't know if this is the fastest way so I am asking for your help. Thanks in advance.
T=25 + 273;
Tmax= 1100+273;
h=0.001;
temporaggiungimento=50;
tmax=100;
passo=( Tmax / temporaggiungimento)*h;
profilo1=linspace(25+273,1100+273,temporaggiungimento/h);
tempo=zeros(1,tmax/h);
profilo=zeros(1,tmax/h);
profilo(1)=25+273;
for j=1:(temporaggiungimento/h-1)
j=j+1
%profilo(j)=profilo(j-1)+passo;
profilo(j)=profilo1(j);
for j=temporaggiungimento/h:(tmax/h)-1
j=j+1;
profilo(j)=1100+273;
end;
end;
0 个评论
采纳的回答
Stephen23
2017-2-3
编辑:Stephen23
2021-2-4
MATLAB's most basic data type is the array, and one can perform many operations on the whole array at once:
Try something like this instead of those loops:
profilo2 = zeros(1,tmax/h);
idx = 1:temporaggiungimento/h;
profilo2(idx) = profilo1;
idy = 1+temporaggiungimento/h:tmax/h;
profilo2(idy) = 1100+273;
And the time difference:
Elapsed time is 0.007594 seconds. % my code
Elapsed time is 108.509334 seconds. % your code
Yet the output is exactly the same:
>> isequal(profilo,profilo2)
ans =
1
More than ten thousand times faster with effective use of arrays:
2 个评论
Stephen23
2017-2-3
编辑:Stephen23
2017-2-3
@Giuseppe Napoli: I am glad to be able to help. If my answer helped you (e.g. sped up your code more than ten thousand times), then please accept my answer. On this forum accepting the best answer is an easy way for you to show that you appreciate our effort (we are volunteers).
更多回答(1 个)
Mina Mino
2023-4-7
I have the same problem and I need to speed up my code in the following form. I would be grateful if anyone can help me. it is so urgent and important for me. Thanks.
%begining of the Code%
clc
clear all
close all
format long g
fid=fopen('list2.txt','r');
if fid==-1
disp('there is an error')
else
end
S = textscan(fid,'%s');
fclose(fid);
i=1;
fnames= S{i,i};
tic
NA=[];
for fiile=1:700
varargout = readhgt(fnames{fiile});
LAT=varargout.lat;LAT(end)=[];
LON=varargout.lon;LON(end)=[];
Z=varargout.z;Z(:,end)=[];
Z(end,:)=[];
% Z_vec=reshape(Z,[12967201,1]);
ROUGH=[];
for row=1:3:3597
for col=1:3:3597
A=[Z(row,col) Z(row,col+1) Z(row,col+2);Z(row+1,col) Z(row+1,col+1) Z(row+1,col+2);Z(row+2,col) Z(row+2,col+1) Z(row+2,col+2)];
Dif=(double(A)-mean(mean(A))).^2;
rough=sqrt(mean(mean(Dif)));
ROUGH=[ROUGH;mean([LAT(row) LAT(row+1) LAT(row+2)]) mean([LON(col) LON(col+1) LON(col+2)]) rough];
end
end
NA=[NA;ROUGH];
end
toc
%end of code
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!