0

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.

slayton
  • 20,123
  • 10
  • 60
  • 89
user1713288
  • 73
  • 1
  • 1
  • 6

2 Answers2

6

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

slayton
  • 20,123
  • 10
  • 60
  • 89
  • 3
    I'm going to add my traditional caveat and remind everyone that MATLAB's `'` operator is the complex conjugate transpose; you should use `.'` for the non-conjugating version. – Edric Oct 08 '12 at 07:24
  • @Edric Hey, that's "my" caveat too! I'm glad to find someone has that same Matlab "pet peeve" :-) – Luis Mendo May 30 '14 at 17:24
3

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.

Community
  • 1
  • 1
Jonas
  • 74,690
  • 10
  • 137
  • 177