Adding the first n elements of an array

11 ビュー (過去 30 日間)
John Slugg
John Slugg 2020 年 4 月 29 日
回答済み: Geoff Hayes 2020 年 4 月 29 日
I am trying to add the first n elements of my array as I go through this loop. Right now I am using lt{k}*k to achieve this addition, however this only works when lt{k} is equal in all entries. for the problem I am trying to solve, the entries are varried.
lt={0.020 0.005 0.020 0.005 0.020};
so I want the value for each iteration to be:
0.020
0.025
0.045
0.050
0.070
this line of code will be used to replace lt{k}*k
zk = cell(n,1);
zk_1 = cell(n,1);
for k = 1:n
zk{k} = (lt{k}*k-(Lt/2));
zk_1{k} = (lt{k}*(k-1)-(Lt/2));
end

回答 (1 件)

Geoff Hayes
Geoff Hayes 2020 年 4 月 29 日
John - given your output, it sounds like you are trying to get the code to do a cumulative sum. If you need to use a for loop, then your calculations need to depend upon the previous iteration.
n = length(lt);
zk = cell(n,1);
zk{1} = lt{1};
for k = 2:n
zk{k} = lt{k} + zk{k-1}; % <--- use previous iteration sum at zk{k-1}
end
Or just use cumsum.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by