For Loop and if statement

7 views (last 30 days)
Zain Abbas
Zain Abbas on 10 Nov 2021
Edited: Kevin Holly on 10 Nov 2021
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

Answers (1)

Kevin Holly
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
a = 3×4
18 7 9 1 15 13 7 2 5 7 8 3
Breakdown:
m(:,4)==1
ans = 5×1 logical array
1 0 1 0 0
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)
ans = 5×1
1 2 1 3 2
Now, let's look at the first three columns 1 through 3.
m(:,1:3)
ans = 5×3
9 6 7 7 8 6 9 1 2 5 7 8 8 5 1
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)
ans = 2×3
9 6 7 9 1 2
Now, let's sum the columns.
sum(m(m(:,4)==1,1:3),1)
ans = 1×3
18 7 9
Now, let's add the 4th column back by concatenating with a bracket.
[sum(m(m(:,4)==1,1:3),1) 1]
ans = 1×4
18 7 9 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
a = 3×4
18 7 9 1 15 13 7 2 5 7 8 3

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!