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

2 views (last 30 days)
Ahsan Khan on 12 Sep 2011
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 on 12 Sep 2011
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(:)
Ahsan Khan on 12 Sep 2011
THANKS alot. worked like a charm. didn't know that this bsxfun function is so diverse and powerful...thanks again

David Young on 12 Sep 2011
nrows = size(B,1);
C = zeros(nrows, length(A));
ind = bsxfun(@plus, (1:nrows)', (B-1)*nrows);
C(ind(:)) = B(:);
C = [A; C]
David Young on 13 Sep 2011
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 on 12 Sep 2011
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