简体   繁体   English

使用Matlab查找矩阵中相等元素的位置

[英]Find the position of equal elements in a matrix using Matlab

Suppose I have: 假设我有:

m = [1,2,3;1,4,5;6,4,7]

I want to get a list containing the positions of the elements in the matrix m so that the positions of equal elements are grouped together. 我想得到一个包含矩阵m元素位置的列表,以便将相等元素的位置分组在一起。 The output for matrix m must be: 矩阵m的输出必须为:

{{1,1},{2,1}},{{2,2},{3,2}},{1,2},{1,3},{2,3},{3,1},{3,3}
%     1             2         3     4     5     6     7

We can see here that the positions for the elements that are all equal to each other are grouped together. 我们在这里可以看到,彼此相等的元素的位置被分组在一起。

The simplest way would be to loop through every unique value and determine the row and column positions that match each value. 最简单的方法是遍历每个唯一值并确定与每个值匹配的行和列位置。 Something like this could work: 这样的事情可能会起作用:

val = unique(m);
pos = cell(1, numel(val));
for ii = 1 : numel(val)
    [r,c] = find(m == val(ii));
    pos{ii} = [r,c];
end

pos would be a cell array containing all of the positions for each unique value. pos是一个单元格数组,其中包含每个唯一值的所有位置。 We can show what these positions are by: 我们可以通过以下方式显示这些职位:

>> format compact; celldisp(pos)
pos{1} =
     1     1
     2     1
pos{2} =
     1     2
pos{3} =
     1     3
pos{4} =
     2     2
     3     2
pos{5} =
     2     3
pos{6} =
     3     1
pos{7} =
     3     3

This of course is not meaningful unless you specifically show each unique value per group of positions. 除非您明确显示每组头寸的每个唯一值,否则这当然没有意义。 Therefore, we can try something like this instead where we can loop through each element in the cell array as well as display the corresponding element that each set of positions belongs to: 因此,我们可以尝试使用类似的方法,其中我们可以遍历单元格数组中的每个元素,并显示每个位置集所属的对应元素:

 for ii = 1 : numel(val)
     fprintf('Value: %f\n', val(ii));
     fprintf('Positions:\n');
     disp(pos{ii});
 end

What I get is now: 我现在得到的是:

Value: 1.000000
Positions:
     1     1
     2     1
Value: 2.000000
Positions:
     1     2
Value: 3.000000
Positions:
     1     3
Value: 4.000000
Positions:
     2     2
     3     2
Value: 5.000000
Positions:
     2     3
Value: 6.000000
Positions:
     3     1
Value: 7.000000
Positions:
     3     3

This gives you what you want, except for the fact that indices of unique elements are also wrapped in cell twice, just like the indices of repeating elements: 这将为您提供所需的内容,唯一的事实是唯一元素的索引也会在单元格中包装两次,就像重复元素的索引一样:

m = [1,2,3;1,4,5;6,4,7];

[~, idx] = ismember(m(:), unique(m(:)));
linInd = 1:numel(m);
[i,j] = ind2sub(size(m), linInd);
res = accumarray(idx, linInd, [], @(x) {num2cell([i(x);j(x)]',2)});

Result: 结果:

>> celldisp(res)

res{1}{1} =
     2     1
res{1}{2} =
     1     1
res{2}{1} =
     1     2
res{3}{1} =
     1     3
res{4}{1} =
     2     2
res{4}{2} =
     3     2
res{5}{1} =
     2     3
res{6}{1} =
     3     1
res{7}{1} =
     3     3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM