Search matrix for array of values and place results into another
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Stephen23
2018년 2월 27일
편집: Stephen23
2018년 2월 27일
>> 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
추가 답변 (1개)
Andrei Bobrov
2018년 2월 28일
t = ismember(A',B);
Ct = C';
ii = sort(t,'descend');
out = double(ii);
out(ii) = Ct(t);
out(~ii) = -1;
out = out';
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!