Setting maximum and minimum limits from cumsum function

8 visualizzazioni (ultimi 30 giorni)
Hi,
I'm trying to create a simple model that will calculate the state of charge of a battery, the possible energy flows into/out of the battery are shown below as 'A'.
Positive values are for energy available to change the battery, negative is energy demand on the battery.
A = [1, 4, 3, 3, 1, -2, -5, 1, 2, 3, -5, -5, 1, 1, 1, 3]
If the battery is of size 7, the minimum level of charge will be 0 and the max will be 7.
So far I believe the way to calculate this is by using the cumsum function, however the result of each cumsum should not be less than 0 or more than 7.
So for the above array I would like my results to look as follows, with the afformentioned limits taken into account.
SoC = cumsum(A)
SoC =[1, 5, 7, 7, 7, 5, 0, 1, 3, 6, 1, 0, 1, 2, 3, 6]
Hopefully someone will be able to help me on this, you help is greatly appriciated.

Risposta accettata

Ameer Hamza
Ameer Hamza il 30 Nov 2020
for-loop might be the most efficient solution
A = [1, 4, 3, 3, 1, -2, -5, 1, 2, 3, -5, -5, 1, 1, 1, 3];
B = zeros(size(A));
B(1) = A(1);
lb = 0;
ub = 7;
for i = 2:numel(A)
B(i) = B(i-1) + A(i);
B(i) = max(min(B(i), ub), lb);
end

Più risposte (0)

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by