Replace elements between two matrices
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Ismaeel
am 6 Dez. 2016
Bearbeitet: Ismaeel
am 7 Dez. 2016
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 Kommentare
Akzeptierte Antwort
Image Analyst
am 7 Dez. 2016
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 Kommentare
Weitere Antworten (1)
Chaya N
am 7 Dez. 2016
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 Kommentare
Image Analyst
am 7 Dez. 2016
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?
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!