如何在MATLAB中找到矩阵中具有相同值的元素的行索引?

时间:2019-01-26 17:48:30

标签: matlab matrix find row

我有两个4x1矩阵。它们具有相同的元素,但矩阵中元素的行索引不同。

a = [200;100;100;300]
b = [100;100;200;300]

我需要找到矩阵a中矩阵b的元素的索引号。 例如,矩阵b的第三个元素是200,矩阵a中的索引数200是1。

结果应为= [2 3 1 4]

我编写了这段代码,但是由于有两个100,所以它不起作用:

for i=1:4
    c(1,i) = find(a(:,1) == b(i,1));
end

我收到此警告:Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

要拥有[2 3 1 4]我应该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以sort ab并使用已排序数组的索引来获得所需的结果:

[~,s1] = sort(a);
[~,s2] = sort(b);
c(s2) = s1;