Delete columns of a matrix based on values in other matrix

1 次查看(过去 30 天)
I have 3 matrices. The 2nd column of Matrix #1 counts up from 1 to 200. I want to check the 4th column of matrix #2 and the 10th column of matrix #3. If Matrix #1 contains a value in col2 that matrix 2 col4 or matrix 3 col10 does not have, i want to delete or turn the whole row containing that uncommon values to zeros.
Ex.
Matrix 1 (col2) Matrix 2 (col4) Matrix 3 (col10)
1 2 1
2 3 2
3 4 3
4 5 4
5 7 5
6 8 7
7 9 9
8 10 10
9 11 11
10 12 12
...
In this case, i am looking for rows 1, 6 and 8 to be deleted(or turned to zeros) from Matrix 1. Row 6 of Matrix 2 and row 1 of matrix 3.
Thanks

采纳的回答

Adam Danz
Adam Danz 2019-7-22
编辑:Adam Danz 2019-7-22
Replaces identified rows with zeros.
% Example data that match the indices in your question
M1 = rand(10,10); M1(:,2) = 1:10;
M2 = rand(10,10); M2(:,4) = [2:5,7:12];
M3 = rand(10,10); M3(:,10) = [1:5,7,9:12];
% Identify rows that should be eliminated; replace data with zeros.
idx = ~ismember(M1(:,2),M2(:,4)) | ~ismember(M1(:,2),M3(:,10));
M1(idx,:) = 0;
Note that row 6 should also be altered in addition to row 1 and 8.
If you'd rather delete those rows in M1 rather than replace the values with 0s,
M1(idx,:) = [];
  4 个评论
Conor Nelson
Conor Nelson 2019-7-22
编辑:Conor Nelson 2019-7-22
Doesnt seem to be working correctly for my application of the code (more complex example than the one i supplied above), i will continue to mess around with it
Adam Danz
Adam Danz 2019-7-22
If you attach a mat file with M1, M2, M3 matrices, I can chip in.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by