Find the rows of a matrix A within another matrix B
3 次查看(过去 30 天)
显示 更早的评论
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1437918/image.png)
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 个评论
采纳的回答
Bruno Luong
2023-7-19
编辑:Bruno Luong
2023-7-19
% 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 个评论
更多回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!