Compare rows of two array and store the corresponding column value if the Row elements are equal

6 ビュー (過去 30 日間)
Hello,
I have two matrices where i need to compare the first row element of the first matrix with the first row element of the second matrix.If they are equal then copy the corresponding column element of the first and second matrices into a new array.
for example: I have
A=[1 2;
3 4;
5 6;
7 8];
and
B=[1 8;
2 6 ;
5 9;
6 8];
Now comapre A(1,1) with B(1,1) . Check if(A(1,1)==B(1,1)) Here A(1,1)=1 and B(1,1)=1 So they are equal Now write the correspong column value of both the matrices in new array i.e A(1,2)=2 and B(1,2)=8 So C=[2 8;]; Similarly if (A(2,1)==B(2,1)) here A(2,1)=3 and B(2,1)=2 so they are not equal. So i will not write the column values in C. Similary for all the elements.
Please let me the function in MATLAB to get this. Looking forward to hear from you.
Thanks Pankaja

採用された回答

Guillaume
Guillaume 2015 年 2 月 19 日
Possibly, this is what you want (but did not ask):
A = [1 2; 3 4; 5 6; 7 8];
B = [1 8; 2 6; 5 9];
[~, rowsA, rowsB] = intersect(A(:, 1), B(:, 1));
C = [A(rowsA, 2) B(rowsB, 2)]

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 2 月 19 日
Try this:
A = [1 2; 3 4; 5 6; 7 8];
B = [1 8; 2 6; 5 9; 6 8];
X = A(:,1)==B(:,1);
C = [A(X,2),B(X,2)];
  2 件のコメント
Pankaja Tanjore
Pankaja Tanjore 2015 年 2 月 19 日
Hello , Thanks for the reply. I just wanted to know the above solution suggested by you works only if the dimension of the two matrices are equal. I have matrices of two different dimensions, and I applied the above function for my matrices which have unequal dimension. I am getting an error.
So please let me know about this.
Looking forward for your reply
Thanks
Pankaja
Stephen23
Stephen23 2015 年 2 月 20 日
編集済み: Stephen23 2015 年 2 月 20 日
In your explanation you compared row-by-row, which implies that the number of rows must be the same. The code I gave solves your original question and with the data that you gave. Use Guillame's solution if you actually want to compare all rows values of each matrix.
Do you see that these are different? Comparing each row to the corresponding row in the other matrix vs comparing each row to all rows in the other matrix... which do you want?
The first one is what you asked for.

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

カテゴリ

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