How to speed up for loop with if condition

7 Ansichten (letzte 30 Tage)
Nicolò Monaco
Nicolò Monaco am 17 Mär. 2022
Beantwortet: M.B am 18 Mär. 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.

Akzeptierte Antwort

M.B
M.B am 18 Mär. 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by