user1713288
user1713288

Reputation: 73

Summing across rows of a matrix instead of columns

I have a 21x19 matrix B

Each index of the matrix is either 1,0, or -1. I want to count the number of occurrences for each row and column. Performing the column count is easy:

Colcount = sum( B == -1 );
Colcount = sum( B == 0  );
Colcount = sum( B == 1  );

However accessing the other dimension to attain the row counts is proving difficult. It would be great of it could be accessed in one statement. Then i need to use a fprintf statement to print the results to the screen.

Upvotes: 0

Views: 10768

Answers (2)

slayton
slayton

Reputation: 20319

By default sum operates on the columns of a matrix. You can change this by specifying a second argument to sum. For example:

A = [ 1 1 1; 0 1 0]; 
C = sum(A,2);
C -> [3; 1];

Additionally you can transpose the matrix and get the same result:

A = [ 1 1 1; 0 1 0]; 
C = sum(A');  % Transpose A, ie convert rows to columns and columns to rows
C -> [3 1];  % note that the result is transposed as well

Then calling fprintf is easy, provide it with a vector and it will produce a string for each index of that vector.

fprintf('The count is %d\n', C)

The count is 3

The count is 1

Upvotes: 6

Jonas
Jonas

Reputation: 74940

The second input argument of SUM indicates in which direction you want to sum.

For example, if you want to count the number of occurrences of 1 along rows and columns, respectively, and print the result using fprintf, you can write:

rowCount = sum(B==1,2);
colCount = sum(B==1,1); %# 1 is the default
fprintf('The rowCount of ones is\n%s\nThe colCount of ones is\n%s\n',...
   num2str(rowCount'),num2str(colCount))

Note that I use num2str so that you can easily print a vector.

Upvotes: 3

Related Questions