フィルターのクリア

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

1 回表示 (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by