フィルターのクリア

How to add 1 matrix to another matrix ?

1 回表示 (過去 30 日間)
Ahsan Abbas
Ahsan Abbas 2016 年 4 月 27 日
コメント済み: Ahsan Abbas 2016 年 4 月 30 日
I have 2 matrices with different size as show below and just want to concatenate both of them. I know 2nd matrix have 1st 6 columns entries that are lying in b/w 1st matrix somewhere, so now i just want to add last 2 column values to 1st matrix of there corresponding rows of 1st matrix. Can someone help me how to write syntax for this ?
  4 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 4 月 27 日
This is not clear. post the result to make it clear
Ahsan Abbas
Ahsan Abbas 2016 年 4 月 27 日
x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]; y = [4 5 6 12 15; 10 11 12 25 52]; result would be like z = [1 2 3 0 0; 4 5 6 12 15; 7 8 9 0 0; 10 11 12 25 52];

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

採用された回答

Star Strider
Star Strider 2016 年 4 月 27 日
編集済み: Star Strider 2016 年 4 月 27 日
One approach, taking advantage of the fact that both of your matrices are sorted by the first column:
M1 = sortrows(rand(15, 4), 1); % Create 1st Matrix & Sort By Column #1
M2 = [M1(1:5:end,:) rand(3,2)]; % Create 2nd Matrix & Add Columns #5 & #6
idx = find(ismember(M1(:,1), M2(:,1))); % Find Indices Of Matching Column #1 Entries
M1 = [M1 zeros(size(M1,1),2)]; % Add Zeros To End Of ‘M1’
M1(idx,5:6) = M2(:,5:6); % Fill Columns #5 & #6 With Same Values From ‘M2’
Since you are dealing with floating-point numbers, if you have R2015a or later, you would likely best use ismembertol instead of ismember to guarantee that your data match.
  2 件のコメント
Ahsan Abbas
Ahsan Abbas 2016 年 4 月 27 日
Thanks Star Strider for helping, i am using matlab 2013b so ismember is the only option.
Star Strider
Star Strider 2016 年 4 月 27 日
My pleasure.
I’m hoping that your matrix entries are exact, so that ismember will work. If not, we will work on a way to use a tolerance with it. Rounding the first column of each matrix to a particular number of decimal places first would likely be easiest.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 4 月 27 日
[n1,m1]=size(x)
[n2,m2]=size(y)
z=zeros(n1,m2)
idx=ismember(x,y(:,1:m1),'rows')
z(idx,:)=y
z(~idx,1:m1)=x(~idx,:)
  1 件のコメント
Ahsan Abbas
Ahsan Abbas 2016 年 4 月 30 日
Thank you Azzi for your response.

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by