How to speed up for loop with if condition

조회 수: 3 (최근 30일)
Nicolò Monaco
Nicolò Monaco 2022년 3월 17일
답변: M.B 2022년 3월 18일
Hello. I have the following code:
tilt = zeros(length(delta_tilt),width(delta_tilt));
for k= 1:(length(delta_tilt)-1)
tilt(k+1,:)= tilt(k,:)+delta_tilt(k+1,:);
for i= 1:365
if tilt(k+1,i)>constraint_up;
tilt(k+1,i)= constraint_up;
elseif tilt(k+1,i)<constraint_down;
tilt(k+1,i)= constraint_down;
end
end
end
Considering delta_tilt an array 86400*365, computational time for this operation results very heavy. There's any way to speed up this operation?
I want to build "tilt" as the cumsum of delta_tilt, but if the value k of tilt is out of boundaries, I want that the value k+1 takes in consideration this limitation.
Thanks in advance.

채택된 답변

M.B
M.B 2022년 3월 18일
Not sure if it speeds up the code, but you can try the following:
tilt = 0*delta_tilt;
for k = 1:(size(delta_tilt, 1)-1)
tilt(k+1,:)= tilt(k,:)+delta_tilt(k+1,:);
tilt(k+1,:)= min(tilt(k+1,:),constraint_up);
tilt(k+1,:)= max(tilt(k+1,:),constraint_down);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by