For Loop and if statement
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Kevin Holly
on 10 Nov 2021
Edited: Kevin Holly
on 10 Nov 2021
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!