跨矩阵行而不是列求和

跨矩阵行而不是列求和

本文介绍了跨矩阵行而不是列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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

这篇关于跨矩阵行而不是列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 01:54