For loop question with matrix

조회 수: 5 (최근 30일)
Gko K
Gko K 2019년 3월 23일
댓글: Gko K 2019년 3월 25일
I have a matrix as below called A (60x3 double)
A = [10 3.5 -34.66
9 3.5 -35.6
8 3.5 -31.43
7 3.5 -29.04
6 3.5 -27.81
5 3.5 -26.59
4 3.5 -23.69
3 3.5 -16.47
2 3.5 2.94
1 3.5 24.03
5 3.5 25.86
4 3.5 35.98
3 3.5 55.89
2 3.5 91.82
1 3.5 101.5
6 3.5 -63.5
5 3.5 -67.03
4 3.5 -72.58
3 3.5 -80.98
2 3.5 -85.91
1 3.5 -63.15
7 3.5 -20.23
6 3.5 -19.92
5 3.5 -20.05
4 3.5 -19.69
3 3.5 -13.96
2 3.5 11.57
1 3.5 30.76
3 3.5 63.36
2 3.5 99.82
1 3.5 107.13
10 3.5 -47.09
9 3.5 -61.25
8 3.5 -61.89
7 3.5 -63.07
6 3.5 -65.29
5 3.5 -69.63
4 3.5 -76.96
3 3.5 -84.92
2 3.5 -80.39
1 3.5 -57.89]
I want to sum column 2 values until column 1 value is 1. I mean first sum must be on row 1 to row 10, and 2nd sum must be on row 15 to row 20, 3rd sum must be on row 21 to row 26 etc.
How can i do that with using for loop or another way?
  댓글 수: 1
Adam Danz
Adam Danz 2019년 3월 23일
The number 1 is in the following rows of column 1:
>> find(A(:,1)==1)
ans =
10
15
21
28
31
41
so I'm having trouble figuring out what rule you're using to select row numbers.

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

답변 (2개)

Walter Roberson
Walter Roberson 2019년 3월 23일
locs = [find(A(:,1)==1); size(A,1)+1];
tsum = cumsum([0;A(:,2)]);
output = tsum(locs(2:end)) - tsum(locs(1:end-1));
  댓글 수: 10
Adam Danz
Adam Danz 2019년 3월 24일
Yeah, that was unclear to me from the beginning.
Gko K
Gko K 2019년 3월 24일
편집: Gko K 2019년 3월 24일
Ok, thank you both, Sorry if i make you busy.
I have analysis results which are in a big excel table.
I want to split matrix as i show below:
My code runs true if i have 1 matrix. But i have a big table as shown in the pic.I want to run code for matrix 1 then matrix 2 then matrix 3 then matrix 4 then matrix 5 then matrix....n.
If you dont want to help no problem. Thanks for your previous helps friends.

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


Adam Danz
Adam Danz 2019년 3월 24일
편집: Adam Danz 2019년 3월 24일
"I want to sum column 2 values until column 1 value is 1."
With your input matrix "A", 's' is the sum of column 2 for each group.
% Create group numbers for each row
rowGroups = cumsum([0;A(1:end-1,1)] == 1)+1;
% Calculate sum of col 2 for each group
s = splitapply(@sum, A(:,2), rowGroups)
  댓글 수: 5
Adam Danz
Adam Danz 2019년 3월 24일
We've all been there.
Gko K
Gko K 2019년 3월 25일
Thank you

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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by