How to intersect a matrix with a set and keep the rows of the matrix?
Afficher commentaires plus anciens
I'm trying to intersect an N by M matrix, 'A', with a set (a 1 by X matrix), 'B', but am trying to do so by rows. (e.g. A(1:M) intersect B ).
So I would end up with an N by '__' matrix where the rows are the intersection of the respective row and set 'B', rather than a large set.
Is there a way to do this without using a for loop?
6 commentaires
James Tursa
le 24 Août 2015
Can you provide a short example for what it means to intersect an N x M matrix with a 1 x X vector and end up with a N x M matrix?
Rion Wilson-Yue
le 24 Août 2015
Modifié(e) : Rion Wilson-Yue
le 24 Août 2015
James Tursa
le 24 Août 2015
Your example conveniently has the same number of elements in each row of the result. What if this is not the case?
Rion Wilson-Yue
le 24 Août 2015
James Tursa
le 25 Août 2015
There are various ways to do it (padding, cell arrays, etc) ... we just need to know what you want for an output.
Rion Wilson-Yue
le 25 Août 2015
Modifié(e) : Rion Wilson-Yue
le 25 Août 2015
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 25 Août 2015
How about a not-too-fancy but simple, intuitive, and easy to understand "for" loop?
A = randi(20, 2, 15) % Sample data
B = [ 1 2 3 4 5 6 ] % What we're looking for
C = NaN(size(A)); % Preallocate
% Check each row one at a time.
for row = 1 : size(A, 1)
% Find intersection.
B_in_A = intersect(A(row, :), B)
% Stuff them into C
C(row, 1:length(B_in_A)) = B_in_A;
end
% Display C
C
4 commentaires
Rion Wilson-Yue
le 25 Août 2015
Image Analyst
le 25 Août 2015
You're funny. Do you know how fast or slow a for loop even is? I just did one hundred million (yes, 100,000,000) for loop iterations in 0.2 seconds. Just how fast do you need? How many iterations do you plan on doing? Trillions?
The for loop itself is rarely the reason why it's sometimes slightly slower - it's the way the memory is accessed.
Rion Wilson-Yue
le 25 Août 2015
Image Analyst
le 25 Août 2015
Not that I can think of off the top of my head. The problem is that you want your answers row-by-row, and each row has a different number of numbers, so all I can think of is a row-by-row solution.
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!