MATLAB: Replace elements between two matrices

replace elements in two matrices

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

Best Answer

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)