How to speed up for loop with if condition

1 vue (au cours des 30 derniers jours)
Nicolò Monaco
Nicolò Monaco le 17 Mar 2022
Réponse apportée : M.B le 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.

Réponse acceptée

M.B
M.B le 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by