KiW
KiW

Reputation: 593

Matlab - Summing from control variable in loop to end of matrix and from beginning of matrix to control variable

As a part of a bigger script, I have a matrix 1738 * 2 (1738 rows - 2 columns) and I want to loop through the first column (so 1738 times). 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. This is how i try to start with the loop through the first column - COG_Ton is the 1738 x 2 Matrix (the number of rows is dependent on the input-data).

My idea is something like this:

for ik = COG_Ton (:,1)
    tonnes(ik) = sum (COG_Ton (1:ik-1, 2)) 
    tonnes2(ik) = sum(COG_Ton (ik:end,2))
end

Does anyone have an idea how I can implement this in Matlab ?

Upvotes: 0

Views: 23

Answers (2)

Shai
Shai

Reputation: 114796

You can speed things up using cumsum once and observing that tonnes2(k) = sum(COG_Ton(:,2))-tonnes1(k):

cs = cumsum(COG_Ton(:,2), 1);
tonnes1 = cs(COG_Ton(:,1)-1); %// assuming for the k-th entry you sum up to COG_Ton(k,1)-1
tonnes2 = cs(end)-tonnes1;

Upvotes: 0

jkazan
jkazan

Reputation: 1199

The code you've written is quite similar in matlab code, but with some minor changes, see below:

for ik = 1:size(COG_Ton,1) length of column 1 in x
    tonnes(ik) = sum (COG_Ton (1:ik-1, 2));
    tonnes2(ik) = sum(COG_Ton (ik:end,2));
end

note the syntax in the for-statement. ik goes from 1 to size(COG_Ton,1), i.e. the length of column 1, which is 1738 in your example.

Upvotes: 1

Related Questions