Find the rows of a matrix A within another matrix B

2 ビュー (過去 30 日間)
Alberto Acri
Alberto Acri 2023 年 7 月 19 日
編集済み: Bruno Luong 2023 年 7 月 19 日
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

採用された回答

Bruno Luong
Bruno Luong 2023 年 7 月 19 日
編集済み: Bruno Luong 2023 年 7 月 19 日
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

その他の回答 (1 件)

Katy Weihrich
Katy Weihrich 2023 年 7 月 19 日
%% 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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by