Subtracting Matrices in Special way
1 view (last 30 days)
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
Ive J
on 1 Dec 2021
There should be a simpler way, but this works:
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];
% build a new matrix from union of indices
idx = union(A(:, 1), B(:, 1));
D = [idx, zeros(numel(idx), 2)];
% fill x and y for shared indices between A and B
[fa, fb] = ismember(A(:, 1), B(:, 1));
fd = ismember(idx, A(fa, 1));
D(fd, 2:3) = A(fa, 2:3) - B(fb(fa), 2:3);
% fill the remaining rows in D
A(fa, :) = []; B(fb(fa), :) = []; % don't need them anymore!
[fd, fa] = ismember(idx, A(:, 1));
D(fd, 2:3) = A(fa(fd), 2:3);
[fd, fb] = ismember(idx, B(:, 1));
D(fd, 2:3) = D(fd, 2:3) - B(fb(fd), 2:3);
% check if D is same as C
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];
all(D == C, 'all')
More Answers (1)
Stephen23
on 2 Dec 2021
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)
0 Comments
See Also
Categories
Find more on Matrices and Arrays 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!