Subtracting Matrices in Special way
Show older comments
I have a Matrices as:
A=[1 10 12;2 12 3; 3 15 4; 4 16 7; 5 18 9; 6 10 10; 7 12 9; 9 5 6];
B=[3 9 8; 4 8 3; 5 2 5; 7 10 2; 8 9 7; 8 9 7; 9 12 10; 10 5 6];
Where Colum 1 is the index Colum 2 is the x and Colum 3 is the y. I would like to match each index of the 2 matrices and subtract the x and y values. The solution should be something like this:
C=[1 10 12; 2 12 3; 3 6 -4; 4 8 4; 5 16 4; 6 10 10; 7 2 7; 8 -9 -7; 9 -7 -4; 10 -5 -6]
How would I do this?
Accepted Answer
More Answers (1)
If the A values are copied first then only two ISMEMBER are required (simpler, more efficient), nor any resizing or changing of the A & B arrays (more efficient, and in general changing raw input data is best avoided):
A = [1,10,12;2,12,3;3,15,4;4,16,7;5,18,9;6,10,10;7,12,9;9,5,6]
B = [3,9,8;4,8,3;5,2,5;7,10,2;8,9,7;8,9,7;9,12,10;10,5,6]
X = union(A(:,1), B(:,1));
D = [X,zeros(numel(X),2)];
% Copy A values:
[Xd,Xa] = ismember(X,A(:,1));
D(Xd,2:3) = A(Xa(Xd),2:3);
% Subtract B values:
[Xd,Xb] = ismember(X,B(:,1));
D(Xd,2:3) = D(Xd,2:3) - B(Xb(Xd),2:3)
% Compare:
C = [1,10,12;2,12,3;3,6,-4;4,8,4;5,16,4;6,10,10;7,2,7;8,-9,-7;9,-7,-4;10,-5,-6];
isequal(C,D)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!