问题描述
我有一个21x19的矩阵B
I have a 21x19 matrix B
矩阵的每个索引为1,0或-1.我想计算每一行和每一列的出现次数.进行列计数很容易:
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 );
但是,要访问其他维度以获得行数却很困难.可以在一个语句中访问它,这将是很棒的事情.然后,我需要使用fprintf语句将结果打印到屏幕上.
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.
推荐答案
默认情况下,sum
对矩阵的列进行操作.您可以通过指定第二个参数sum来更改它.例如:
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];
此外,您可以transpose
矩阵并获得相同的结果:
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
然后调用fprintf
很简单,为其提供一个向量,它将为该向量的每个索引生成一个字符串.
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)
计数为1
这篇关于跨矩阵行而不是列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!