How to merge two different size matrix logically?

2 ビュー (過去 30 日間)
Cladio Andrea
Cladio Andrea 2015 年 2 月 25 日
編集済み: Cladio Andrea 2015 年 2 月 25 日
Hello everyone, i have one matrix A = [0,1,2,...3600] and another one is B=[2,5,7,3600] what i want is to have matrix C(:,1)=[0,1,2....,3600] C(:,2)=[0,0,2,0,0,5,....3600] it should be as same size as A and if elements of B exist in A and that should be in the second column of C and the rest will be zero. Can you help please?

採用された回答

Thorsten
Thorsten 2015 年 2 月 25 日
編集済み: Thorsten 2015 年 2 月 25 日
Like this?
A = [0, 1, 2, 3, 4, 5, 7, 10];
B = [2, 5, 7];
C(:,1) = A;
C(end,2) = 0;
% ind = arrayfun(@(x)(find(x==A)), B);
% or
ind = find(ismember(A,B))
C(ind,2) = A(ind);
  1 件のコメント
Cladio Andrea
Cladio Andrea 2015 年 2 月 25 日
編集済み: Cladio Andrea 2015 年 2 月 25 日
Hi Thorsten i have one more question, i would be very glad if you can answer, lets say now i need another matrix D lets say that counts the number of occurrence of the ones inside B matrix and then insert in the same size matrix let say:
A = [0, 1, 2, 3, 4, 5, 7, 10];
B = [2, 5, 7];
you found :
C = [0,0,2,0,0,5,7,0]; but in that case what i want is the occurence:
D = [0,0,1,0,0,1,1,0]
lets say i have something
A = [0, 1, 2, 3, 4, 5, 7, 10];
B = [2,5,5,7];
still C is the same but i want D also which should be:
C = [0,0,2,0,0,5,7,0];
D = [0,0,1,0,0,2,1,0];
<do you know how to solve that, thank you in advance

サインインしてコメントする。

その他の回答 (2 件)

dpb
dpb 2015 年 2 月 25 日
C=[A zeros(size(A)]; % allocate
C(ismember(A,B),2)=B; % merge by position

Cladio Andrea
Cladio Andrea 2015 年 2 月 25 日
i love you guys!! i was dealing with that problem for hours and now i have 2 perfect answers!!!! Thank you so much!!!

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by