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.
0 个评论
采纳的回答
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(:)
更多回答(2 个)
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
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
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!