How to speed up for loop with if condition

1 visualizzazione (ultimi 30 giorni)
Nicolò Monaco
Nicolò Monaco il 17 Mar 2022
Risposto: M.B il 18 Mar 2022
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.

Risposta accettata

M.B
M.B il 18 Mar 2022
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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by