Find the rows of a matrix A within another matrix B

2 views (last 30 days)
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

Accepted Answer

Bruno Luong
Bruno Luong on 19 Jul 2023
Edited: Bruno Luong on 19 Jul 2023
Use ismember command with 'row' option
% Generate some dymmy date for testing
B=randi(4,10,2)
B = 10×2
1 4 4 4 3 2 4 2 4 3 3 2 1 4 2 1 2 2 2 4
A=randi(4,10,2)
A = 10×2
1 4 2 3 4 2 2 3 1 1 1 1 2 2 1 2 1 4 4 3
% Engine
B_new = B;
B_new(ismember(B,A,'row'),:) = 0;
% Check the result
B_new
B_new = 10×2
0 0 4 4 3 2 0 0 0 0 3 2 0 0 2 1 0 0 2 4

More Answers (1)

Katy Weihrich
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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!