如何从matlab中具有相同大小的几个矩阵中选择具有较高出现次数的值?

时间:2012-09-22 11:05:17

标签: matlab matrix

我希望有一个程序可以执行以下操作:

  • 读取几个大小相同的矩阵(1126x1440双)

  • 选择每个单元格中最常出现的值(相同的i,j矩阵)

  • 将此值写入相应i,j位置具有相同大小1126x1440的输出矩阵中,以使该输出矩阵在每个单元格中具有来自所有输入矩阵的相同位置的最大值。

2 个答案:

答案 0 :(得分:3)

基于@angainor的回答,我认为使用mode函数有一种更简单的方法。

nmatrices - number of matrices
n, m      - dimensions of a single matrix
maxval    - maximum value of an entry (99) 

首先将数据组织成具有维度[n X m X nmatrices]的3-D矩阵。例如,我们可以以三维形式生成以下随机数据:

CC = round(rand(n, m, nmatrices)*maxval); 

然后计算最常见的值是一行:

B = mode(CC,3);   %compute the mode along the 3rd dimension

答案 1 :(得分:0)

以下是您需要的代码。我已经介绍了一些常量:

nmatrices - number of matrices
n, m      - dimensions of a single matrix
maxval    - maximum value of an entry (99)

我首先使用rand生成示例矩阵。矩阵被改变为向量并在CC矩阵中连接。因此,CC的维数是[m * n,nmatrices]。 CC的每一行都包含所有矩阵的单个(i,j)值 - 您想要分析的那些。

CC = [];
% concatenate all matrices into CC
for i=1:nmatrices
    % generate some example matrices
    % A = round(rand(m, n)*maxval);
    A = eval(['neurone' num2str(i)]);
    % flatten matrix to a vector, concatenate vectors
    CC = [CC A(:)];
end

现在我们做真正的工作。我必须转换CC,因为matlab适用于基于列的矩阵,所以我想分析CC的各个列,而不是行。接下来,使用histc,我在CC的每一列中找到最频繁出现的值,即在所有矩阵的(i,j)条目中。 histc在CC的每一列中计算落入给定箱(在您的情况下为-1:maxval)的值。

% CC is of dimension [nmatrices, m*n]
% transpose it for better histc and sort performance
CC = CC';
% count values from 1 to maxval in every column of CC
counts = histc(CC, 1:maxval);

计数具有维度[maxval,m * n] - 对于原始矩阵的每个(i,j),您知道表示1:maxval的给定值的次数。现在要做的最后一件事是对计数进行排序并找出,这是最常出现的计数。我不需要排序的计数,我需要排列,告诉我,来自计数的哪个条目具有最高值。这正是你想要找到的。

% sort the counts. Last row of the permutation will tell us, 
% which entry is most frequently found in columns of CC
[~,perm] = sort(counts);

% the result is a reshaped last row of the permutation
B = reshape(perm(end,:)', m, n);

B就是你想要的。