Find the rows of a matrix A within another matrix B
2 views (last 30 days)
Show older comments
Hi. I need to find the rows of matrix A (106x2) inside matrix B (172x2).
Matrix A should contain the values of all rows within B. Therefore, initially, I would like to know if there is a way to understand if all matrix A is contained in matrix B.
My goal, however, is to create a new matrix B ('B_new') characterized by '0's in the case where a row of A coincides with a row of B.
I explain this better with this image:
There is probably a more effective method than what I have written, like using the 'find' command.
At the moment I am using this code:
A = importdata("matrix_int.mat");
B = importdata("matrix_ext.mat");
B_new = {};
for K = 1:length(A)
row_A = A(K,:);
for K1 = 1:length(B)
row_B = B(K1,:);
if row_A == row_B
row_B = [0,0];
end
B_new = [B_new;{row_B}];
end
end
0 Comments
Accepted Answer
Bruno Luong
on 19 Jul 2023
Edited: Bruno Luong
on 19 Jul 2023
% Generate some dymmy date for testing
B=randi(4,10,2)
A=randi(4,10,2)
% Engine
B_new = B;
B_new(ismember(B,A,'row'),:) = 0;
% Check the result
B_new
0 Comments
More Answers (1)
Katy Weihrich
on 19 Jul 2023
%% example data generation
A = rand(10,2);
B = [rand(2,2); A(1:2,:); rand(2,2); A(5:7,:); rand(2,2); A(3:4,:); rand(2,2); A(1:2,:)];
% note:
%% prep dataoutput
B_new = B;
%% seach for overlaps between A & B rows
% intersect will not obly give you the similarities between the arrays, but
% also the first (!) instance of them overlapping
[~,ia,ib] = intersect(A,B,'rows');
%% set oerlap to 0 in the dataoutput
B_new(ib,:) = 0;
% note: since intersept only gives you the first occurence, if a row in A
% repeatetly occures in B there will some missed rows
%% repeat untill all overlaps are identified
B_prev = B;
while ~all(all(B_prev == B_new))
B_prev = B_new; %
[~,ia,ib] = intersect(A,B_new,'rows');
B_new(ib,:) = 0;
end
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!