代码之家  ›  专栏  ›  技术社区  ›  user2018

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

  •  1
  • user2018  · 技术社区  · 7 年前

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

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

    例如,矩阵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 回复  |  直到 7 年前
        1
  •  2
  •   rahnema1    7 年前

    你可以 sort a b 并使用排序数组的索引来获得所需的结果:

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