Azzera filtri
Azzera filtri

create columns with for loop

1 visualizzazione (ultimi 30 giorni)
JessHmann
JessHmann il 20 Mag 2019
Commentato: JessHmann il 21 Mag 2019
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 Commenti
Bob Thompson
Bob Thompson il 20 Mag 2019
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 il 20 Mag 2019
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

Accedi per commentare.

Risposta accettata

Rik
Rik il 20 Mag 2019
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 Commento
JessHmann
JessHmann il 21 Mag 2019
Thank you very much! That worked perfectly! :)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by