complicated vectorization of for loop wich icludes if and referes back to last loop iteration results

3 views (last 30 days)
Abdelrahman Amer on 11 Jan 2023
Edited: Jan on 11 Jan 2023
I have heard, that it's possible to vectorize for loops even if the for loops are containing conditions and refer back to the results of the last loop iteration. Here a simple version of the code I am trying to voctorize.
Battery_storage = zeros(1, 365); % Value between 0 (empty) and 100 (full)
PV_power_available = round(rand(1,365)); % Random values of 0 and 1
% Look for every day, if the battery van be loaded or not:
for i =2:365
if Battery_storage(i-1)<80 && PV_power_available(i) == 1
Battery_storage(i) = Battery_storage(i-1) + 20;
else
if Battery_storage(i-1) > 20
Battery_storage(i) = Battery_storage(i-1) - 20;
else
Battery_storage(i) = 0;
end
end
end
You would insanely help me, if you could provide me some feedback how to vectorize such a code. The "normal" code takes hours to run by using big for loops and many ifs. So I am trying to make it less time consuming.

Jan on 11 Jan 2023
Edited: Jan on 11 Jan 2023
Why do you assume, that a vectorization is faster? Neither loops nor IF-conditions are slow in modern Matlab versions.
for i = 2:365
if Battery_storage(i-1)<80 && PV_power_available(i) % == 1
Battery_storage(i) = Battery_storage(i-1) + 20;
elseif Battery_storage(i-1) > 20
Battery_storage(i) = Battery_storage(i-1) - 20;
% else % 0 is the default already...
% Battery_storage(i) = 0;
end
end
If PV_power_available is 0 or 1, you can omit the "==1".
This code cannot be vectorized.
Are you sure that this part is the bottleneck of your code?