How to match and two matrix elements and place it under one matrix...let me explain

조회 수: 2 (최근 30일)
Ok so I have one matrix A and one matrix B.
Matrix A is basically an array 1-10.
eg: A = [1 2 3 4 5 6 7 8 9 10];
Matrix B is a Matrix consisting of 5 random integers(1-10)(nx5) eg: B = [1 4 5 8 9;2 3 8 9 10; 1 2 4 7 8; ...]; %and so on.
Now wat i want to do is create a matrix C in which the matching elements will show up in an organized way. let me show you how the resultant matrix C should look like;
1 2 3 4 5 6 7 8 9 10 <-------this is from matrix A
1 0 0 4 5 0 0 8 9 0 <--------this and the rest is from B
0 2 3 0 0 0 0 8 9 10 aligned with A, the empty(non
1 2 0 4 0 0 7 8 0 0 matched elements can be
zero,0,or Nan)
but the matching numbers should be actual numbers not LOGIC of 1s for match and 0 for no-match. is this possible. any suggestions? thanks in advance.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 9월 12일
C = bsxfun(@times,cell2mat(arrayfun(@(i1)ismember(A,B(i1,:)),(1:size(B,1))','un',0)),A)
more variant
[m n] = size(B);
C = zeros(m,numel(A));
[~,ind] = ismember(B(:),A);
idx = sub2ind([m numel(A)],repmat((1:m)',n,1),ind)
C(idx) = B(:)
  댓글 수: 1
Ahsan Khan
Ahsan Khan 2011년 9월 12일
THANKS alot. worked like a charm. didn't know that this bsxfun function is so diverse and powerful...thanks again

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

David Young
David Young 2011년 9월 12일
nrows = size(B,1);
C = zeros(nrows, length(A));
ind = bsxfun(@plus, (1:nrows)', (B-1)*nrows);
C(ind(:)) = B(:);
C = [A; C]
  댓글 수: 4
Andrei Bobrov
Andrei Bobrov 2011년 9월 12일
More work is needed for solving such an example:
A =[38 42 6 43 30 5]
B = [38 6 30;42 43 5;38 30 5]
David Young
David Young 2011년 9월 13일
Yes - I didn't do that because it made for more complexity that perhaps was called for given the original statement of the problem. But you are right - my solution makes restrictive assumptions, and it would be better to add the indexing to make it general.

댓글을 달려면 로그인하십시오.


TAB
TAB 2011년 9월 12일
Sz=size(B);
C=zeros(Sz(1),10)
for Br=1:Sz(1)
for Bc=1:5
for Ac=1:10
if(B(Br,Bc)==A(Ac))
C(Br,Ac)=A(Ac);
end
end
end
end

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by