For Loop and if statement
조회 수: 6 (최근 30일)
이전 댓글 표시
Can someone explain how can use for loop for a data where i have 4 columns as shown below and for each of 3 categories i want to sum the the corresponding x y and z values?
x y z category
9 6 7 1
7 8 6 2
9 1 2 1
5 7 8 3
8 5 1 2
댓글 수: 0
답변 (1개)
Kevin Holly
2021년 11월 10일
편집: Kevin Holly
2021년 11월 10일
m = [9 6 7 1
7 8 6 2
9 1 2 1
5 7 8 3
8 5 1 2];
a=[];
for i=1:3
a = [a; [sum(m(m(:,4)==i,1:3),1) i]];
end
a
Breakdown:
m(:,4)==1
The above creates a logical array of all row in the matrix (m) where the 4 column is equal to 1.
The specific elements within the matrix were selected as m(rows,columns). A colon (:) was used for rows, indicating to select all rows, which in this case was 5. This could also be describe as an array from 1 to 5 or 1:5. For the columns, only the 4th was selected, thus you end up with m(:,4).
m(:,4)
Now, let's look at the first three columns 1 through 3.
m(:,1:3)
Let's use the logical array to select only the one where the 4th column in matrix m is equal to one.
m(m(:,4)==1,1:3)
Now, let's sum the columns.
sum(m(m(:,4)==1,1:3),1)
Now, let's add the 4th column back by concatenating with a bracket.
[sum(m(m(:,4)==1,1:3),1) 1]
Finally, replace the 1 with an i and create a for loop to calculate for catergories 1 through 3. The variable a is created to hold the results in a single matrix. Each result is appended as a row.
a=[];
for i=1:3
a = [a; [sum(m(m(:,4)==i,1:3),1) i]];
end
a
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!