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

1 view (last 30 days)
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
% Load Battery by 20
Battery_storage(i) = Battery_storage(i-1) + 20;
else
% Deload Battery by 20
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.
Thanks ahead

Answers (1)

Jan
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.
Your code can be simplified:
for i = 2:365
if Battery_storage(i-1)<80 && PV_power_available(i) % == 1
% Load Battery by 20
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?

Community Treasure Hunt

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

Start Hunting!