我有一个21x19矩阵 B
矩阵的每个索引都是1,0或-1.我想计算每行和每列的出现次数.执行列计数很简单:
Colcount = sum( B == -1 );
Colcount = sum( B == 0 );
Colcount = sum( B == 1 );
Run Code Online (Sandbox Code Playgroud)
然而,访问其他维度以获得行计数证明是困难的.在一个声明中可以访问它会很棒.然后我需要使用fprintf语句将结果打印到屏幕上.
默认情况下,sum操作矩阵的列.您可以通过指定sum的第二个参数来更改此值.例如:
A = [ 1 1 1; 0 1 0];
C = sum(A,2);
C -> [3; 1];
Run Code Online (Sandbox Code Playgroud)
另外,您可以transpose使用矩阵并获得相同的结果:
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
Run Code Online (Sandbox Code Playgroud)
然后调用fprintf很容易,为它提供一个向量,它将为该向量的每个索引生成一个字符串.
fprintf('The count is %d\n', C)
Run Code Online (Sandbox Code Playgroud)
伯爵数是3
计数是1