Setting maximum and minimum limits from cumsum function

8 次查看(过去 30 天)
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.

采纳的回答

Ameer Hamza
Ameer Hamza 2020-11-30
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by