Setting maximum and minimum limits from cumsum function

8 ビュー (過去 30 日間)
Barry Bambury
Barry Bambury 2020 年 11 月 30 日
コメント済み: Ameer Hamza 2020 年 12 月 1 日
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
  2 件のコメント
Barry Bambury
Barry Bambury 2020 年 12 月 1 日
Perfect Ameer, thank you so much!
Ameer Hamza
Ameer Hamza 2020 年 12 月 1 日
I am glad to be of help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by