MATLAB Answers

Create matrix row element if row elements of two previous matrices are identical

2 views (last 30 days)
Arne
Arne on 26 Nov 2014
Commented: Guillaume on 2 Dec 2014
Sorry for the title. I could not think of something better.
I have the following problem.
I have two four-column matrices build up like this:
Property | X | Y | Z
The two matrices have different sizes, since matrix 1 has a large amount of additional rows compared to matrix 2.
What I want to do is the following:
I need to create a third matrix that only features those rows (of the large matrix) that are identical in columns X, Y and Z to rows in matrix2(the property column is always different).
I tried an if-statement but it did not really work out due to my programming syntax. Has somebody a tip?
Thank you!
Example - I tried something like this: (in this case A is the larger matrix and I want its property column for X,Y,Z-positions that are identical to another matrix B.. I am terrible with the MatLab-syntax..:
if (A(:,2) == B(:,2) and (A(:,3) == B(:,3) and (A(:,4) == B(:,4))
newArray(:,1) = A(:,1);
end
I fear that in the way depicted in the code example it might cancel since A and B are of different size and it cannot really compare

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 26 Nov 2014
Use either intersect (if there's no duplicate X|Y|Z triplet or if you just want one of these triplets) or ismember (if you do want those duplicates in the output. Both are two be used with the 'rows' option:
A = [1 1 2 3
2 3 2 1
3 4 5 6
4 7 8 9
5 1 2 3];
B = [-1 1 2 3
-2 4 5 6
-3 3 2 1];
%with intersect, row 4 of A is removed (not in B), row 5 is removed (triplet already present)
[~, idx] = intersect(A(:, [2 3 4]), B(:, [2 3 4]), 'rows');
C1 = A(idx, :)
%with ismember, row 4 of A is removed (not in B)
C2 = A(ismember(A(:, [2 3 4]), B(:, [2 3 4]), 'rows'), :)

  2 Comments

Guillaume
Guillaume on 2 Dec 2014
You would be indeed better off starting a new question, as most people won't look at activity on questions marked answers. In fact, I only spotted your new comment because it jumped to the top of my answer page. Had I answered another question in the meantime, I would have never noticed your comment.

Sign in to comment.

More Answers (1)

Thorsten
Thorsten on 26 Nov 2014
In this example A is the large matrix and B the small one
A = round(10*rand(10, 3)); A = [A; A(1:2, :)];
B = A(1:2:end, :);
A = [rand(size(A, 1), 1) A];
B = [rand(size(B, 1), 1) B];
Create the new A
Anew = A(ismember(A(:, 2:4), B(:, 2:4), 'rows'), :);

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by