【发布时间】:2012-03-02 16:04:32
【问题描述】:
我有一个矩阵 A 。 我想找到所有独特的元素是 A 所以: b = 唯一(A);将给出 A 中所有唯一元素的数组。
我想找到这些元素在A中的位置。准确的说是b中的元素 在 A 中重复自己,我想为 b 中的每个元素找到它在 A 中的 rows。
如何在没有循环的情况下做到这一点?
【问题讨论】:
标签: matlab
我有一个矩阵 A 。 我想找到所有独特的元素是 A 所以: b = 唯一(A);将给出 A 中所有唯一元素的数组。
我想找到这些元素在A中的位置。准确的说是b中的元素 在 A 中重复自己,我想为 b 中的每个元素找到它在 A 中的 rows。
如何在没有循环的情况下做到这一点?
【问题讨论】:
标签: matlab
命令
[b,m,n] = unique(A);
应该为您提供回答问题所需的所有数据。
【讨论】:
以下是一些示例代码,可以完成我认为您正在尝试做的事情:
%Test data
A = [...
1 2 3 4; ...
4 5 6 7; ...
8 1 3 4];
%Basic "unique" call
[B, ix_A, ix_B] = unique(A);
%Note that the indexes from unique can be used as follows
isequal(A(ix_A), B ) %Returns true
isequal(B(ix_B), A(:) ) %Returns true
%To find a row (and column) in A where each element in B can be found we
%just need to convert the linear indexs into row/column subscripts
[row, column] = ind2sub(size(A), ix_A);
% Note that in general, multiple rows will contain each value from A.
% This will always produce one of the rows (and columns), pracitcially,
% it looks like to returns the last row containing the value.
【讨论】:
unique 支持'first' 和'last' 关键字。这是一个很好的提示。