MATLAB Answers

Replace elements between two matrices

7 ビュー (過去 30 日間)
Ismael
Ismael 2016 年 12 月 6 日
編集済み: Ismael 2016 年 12 月 7 日
I have two matrices A and B:
A= [8 1;
16 2];
B= [8 10;
16 5]
I want to replace any element in B that exist in the 1st column of A, by its corresponding value in the second column of A. The result should be:
C=[1 10;
2 5];
Thanks for help

  0 件のコメント

サインイン to comment.

採用された回答

Image Analyst
Image Analyst 2016 年 12 月 7 日
Try this:
A= [8 1;
16 2]
B= [8 10;
16 5]
% If A & B are integers
rowsToReplace = A(:, 1) == B(:, 1)
C = B; % Initialize C to B.
% Now, replace the rows that need replacing:
C(rowsToReplace, 1) = A(rowsToReplace, 2)

  2 件のコメント

Ismael
Ismael 2016 年 12 月 7 日
That is what I was looking for, thank you so much.
Ismael
Ismael 2016 年 12 月 7 日
Image Analyst, sorry but how about if size(A)~=size(B)? I have a case in this pattern.

サインイン to comment.

その他の回答 (1 件)

Chaya N
Chaya N 2016 年 12 月 7 日
Try the setxor function. You may need to tweak the directionality of the inputs a bit, so use something like
C = setxor(A',B','rows')'

  3 件のコメント

Image Analyst
Image Analyst 2016 年 12 月 7 日
Ismael's "Answer" moved here since it's really a comment to Chaya N:
Thanks Chaya but that did not work, it deals with the whole row while I need any similar elements. Look at the same example with one different element:
A= [4 1;
16 2];
B= [8 10;
16 5];
here we have one element in the first column of B different than A
Matlab returns:
C =
1 4 8 10
2 16 16 5
The true answer should be:
C = [8 10;
2 5]
Image Analyst
Image Analyst 2016 年 12 月 7 日
Ismael, this code:
A= [8 1;
16 2]
B= [8 10;
16 5]
C = setxor(A',B','rows')'
gives
A =
8 1
16 2
B =
8 10
16 5
C =
1 10
2 5
which is the C you originally asked for. Now you're giving a different desired value for C. Which is it?
Ismael
Ismael 2016 年 12 月 7 日
That is true for the case when the first column in A and B are the same. How about if some elements of the 1st column of B are not similar to the elements in the 1st column of A. If, for instance, the element (1,1) in B which is =8 is any number except 8, I don't want to keep different elements and replace similars with their corresponding second column in A.
Simply,
if B(i,1)==A(i,1)
replace B(i,1) with A(i,2)
otherwise don't change

サインイン to comment.

サインイン してこの質問に回答します。


Translated by