create columns with for loop

조회 수: 1 (최근 30일)
JessHmann
JessHmann 2019년 5월 20일
댓글: JessHmann 2019년 5월 21일
Hello,
I am trying to get the cumultive sum of a column but only between certain rows. The rows are found based on a condition and stored in an array(Rows_I_need). For example [500 1000, 2500].
I want to create the cumulitive sum of row 1-499, 500-999, 1000-2499, 2500-end. I have working code for the start and end section and have created a for-loop for the middle section. My problem is, that the for-loop creates the cumlitive sum between rows 500-999 and then takes the last value as a starting point for the next section rows 1000-2499.
Below is an image explaining the problem and my code:
Sum.PNG
Rows_I_need=find(FlowData.weightDiffAfter<-0.5); %find sections
c0=cumsum(column1(1:Rows_I_need(1)-1));%cumsum of first section
h=length(Rows_I_need);
c_last=cumsum(column1(Rows_I_need(a):length(column1))); %cumsum of last section
for a=(length(Rows_I-need)-1)
for k=Rows_I_need
c1=cumsum(column1((k:k(a+1)-1)));
end
end
  댓글 수: 2
Bob Thompson
Bob Thompson 2019년 5월 20일
What is 'column1?'
I don't see why you need both for loops. You should be able to remove the to loop through the values. Also, am I incorrect that k appears to be a single value? How are you indexing k?
k(a+1)
JessHmann
JessHmann 2019년 5월 20일
column1 is the column of my table that I would like to create the cumulitave sum of for the specified rows.
k is the value of the rows stored in the array. For example if k is [500 1000 2500] I want to create the cumulitive sum of rows 500-999 and rows 1000-2499.
I am quite new to programming and was using (k(a+1)-1) to get the second/next element of the array. I have commented my code for further understanding. Thank you for your help! :)
%Rows_I_need is an array with the values [500 100 2500]
for a=(length(Rows_I-need)-1) %a is 2 so the loop will run twice
for k=Rows_I_need
c1=cumsum(column1((k:k(a+1)-1))); %k(a+1)-1 refers to the next element of the array
end
end

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2019년 5월 20일
This should help you solve it:
Rows_I_need=[500, 1000, 2500];
%generate random array as input
array=randi(3,4000,1);
%get cumsum
output=cumsum(array);
for k=1:numel(Rows_I_need)
%subtract the value before the new start-point from all subsequent
%points
one_value_up=output(Rows_I_need(k)-1);
output(Rows_I_need(k):end)=output(Rows_I_need(k):end)-one_value_up;
end
  댓글 수: 1
JessHmann
JessHmann 2019년 5월 21일
Thank you very much! That worked perfectly! :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by