Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Summing from control variable in loop to end of loop / from beginning

1 回表示 (過去 30 日間)
Kian
Kian 2016 年 5 月 9 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have a matrix 1738 * 2 and I want to loop through the first column. Dependent on the iteration of the loop I would like to sum up the the second column from the start value to the (control variable - 1) and from the control variable to the end of the second column. Thanks for every advice

回答 (1 件)

Weird Rando
Weird Rando 2016 年 5 月 9 日
編集済み: Weird Rando 2016 年 5 月 9 日
Don't necessary need a loop you could do something like this
startValue = 2;
control = 10;
a=[1:1:1738; 11:1:1748]';
a1 = sum(a(:,1))
a2 = sum(a(startValue:(control - 1),1))
  2 件のコメント
Kian
Kian 2016 年 5 月 9 日
Thanks for your answer. Unfortunately i need the loop as it is part of a bigger script. This is how i try to start with the loop through the first column - COG_Ton is the 1738 x 2 Matrix (although this is also variable on the input data). for ik = COG_Ton (:,1)
so i am looking for something like: tonnes(ik) = sum (COG_Ton (1:ik-1, 2)) and tonnes2(ik) = sum(COG_Ton (ik:end,2)) but i dont know how to write this in matlab
Weird Rando
Weird Rando 2016 年 5 月 10 日
編集済み: Weird Rando 2016 年 5 月 11 日
I think you when wrong is when you initialise the for loop statement. It gives the COG_Ton values. So if COG_Ton(1,1) = 1024,
tonnes(1024) = sum(COG_Ton(1:1024-1,2)).
If that number exceed the length of COG_Ton you will incur an error.
Here my solution.
nloop = size(COG_Ton,1)-1;
for ik = 1:nloop
tonnes(ik) = sum (COG_Ton (1:ik, 2));
tonnes2(ik) = sum(COG_Ton (ik+1:end,2));
end
However if you did that, you would probably need to amend your code if there were some other code inside that for loop that uses ik and replace that as COG_Ton(ik,1).

Community Treasure Hunt

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

Start Hunting!

Translated by