Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 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(:)
  1 commentaire
Ahsan Khan
Ahsan Khan le 12 Sep 2011
THANKS alot. worked like a charm. didn't know that this bsxfun function is so diverse and powerful...thanks again

Connectez-vous pour commenter.

Plus de réponses (2)

David Young
David Young le 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]
  4 commentaires
Andrei Bobrov
Andrei Bobrov le 12 Sep 2011
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 le 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.

Connectez-vous pour commenter.


TAB
TAB le 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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by