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