How Can i speed up "for" loop ?
조회 수: 26 (최근 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!