Search matrix for array of values and place results into another

1 view (last 30 days)
I am attempting to search mat A for values B. Then take the indices where B is located in A and access the corresponding indices in mat C. Once the values are accessed from C they need to be brought to a front of each row and the rest of the row filled with -1, I can do this with for loops and binary operators or is member function, but it takes a very long time. The pattern is shown below and should be identifiable from looking at it.
if true
A = [ 2 87 35 9 82 3;
77 6 7 92 14 5;
98 64 4 8 33 17;
71 7 54 34 2 8;
9 1 13 18 2 7]
B = 1:10
C = [ 44 32 2 13 22 98;
67 43 87 67 46 23;
87 34 55 22 13 8;
3 98 76 23 29 4;
87 66 43 26 83 23]
Out = [ 44 13 98 -1 -1 -1;
43 87 23 -1 -1 -1;
55 22 -1 -1 -1 -1;
98 29 4 -1 -1 -1;
87 66 83 23 -1 -1]
end

Accepted Answer

Stephen23
Stephen23 on 27 Feb 2018
Edited: Stephen23 on 27 Feb 2018
>> A = [2,87,35,9,82,3;77,6,7,92,14,5;98,64,4,8,33,17;71,7,54,34,2,8;9,1,13,18,2,7];
>> B = 1:10;
>> C = [44,32,2,13,22,98;67,43,87,67,46,23;87,34,55,22,13,8;3,98,76,23,29,4;87,66,43,26,83,23];
>> idm = ismember(A,B);
>> D = C;
>> D(~idm) = -1;
>> [~,idc] = sort(idm,2,'descend');
>> S = size(D);
>> idr = ndgrid(1:S(1),1:S(2));
>> idx = sub2ind(S,idr,idc);
>> D = D(idx)
D =
44 13 98 -1 -1 -1
43 87 23 -1 -1 -1
55 22 -1 -1 -1 -1
98 29 4 -1 -1 -1
87 66 83 23 -1 -1

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 28 Feb 2018
t = ismember(A',B);
Ct = C';
ii = sort(t,'descend');
out = double(ii);
out(ii) = Ct(t);
out(~ii) = -1;
out = out';

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!