Setting maximum and minimum limits from cumsum function

8 vues (au cours des 30 derniers jours)
Barry Bambury
Barry Bambury le 30 Nov 2020
Commenté : Ameer Hamza le 1 Déc 2020
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.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 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
  2 commentaires
Barry Bambury
Barry Bambury le 1 Déc 2020
Perfect Ameer, thank you so much!
Ameer Hamza
Ameer Hamza le 1 Déc 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by