1

我想要一个执行以下操作的程序:

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

  • 选择每个单元格中出现次数最多的值(矩阵中的 i、j 相同)

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

4

2 回答 2

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 矩阵。例如,我们可以生成以下 3-D 形式的随机数据:

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

然后最频繁值的计算是一行:

B = mode(CC,3);   %compute the mode along the 3rd dimension
于 2012-09-22T13:48:39.653 回答
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是你想要的。

于 2012-09-22T12:51:26.183 回答