How to speed up for loop with if condition

1 回表示 (過去 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 Center および File ExchangeLoops 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