简体   繁体   中英

How to find row indexes of elements which have same value in a matrix in MATLAB?

I have two 4x1 matrixes. They have the same elements but the row indexes of elements in the matrixes are different.

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

I need to find index numbers of matrix b's elements in matrix a. For example, the third element of matrix b is 200 and the index number of 200 in matrix a is 1.

The result should be = [2 3 1 4]

I wrote this code but it didn't work because there are two 100s:

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

I have this warning: Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

What should I do to have [2 3 1 4] ?

You can sort a and b and use indexes of the sorted arrays to get the desired result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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