How to remove some arrays in a matrix
1 次查看(过去 30 天)
显示 更早的评论
Suppose I have a matrix m:
m = [3;5;6;1;2;8;5;2;9;1;2;7;8;3;4;9;3];
and restricted matrices r1 and r2:
r1 = [5;1;9;3];
r2 = [6;4];
I need a new matrix mm that its included all arrays of matrix m except arrays in matrix r1 and r2:
mm = [2;8;2;2;7;8];
0 个评论
采纳的回答
Star Strider
2014-11-10
编辑:Star Strider
2014-11-10
You could combine these two lines into one, but I left them separate to make the code more readable:
m = [3;5;6;1;2;8;5;2;9;1;2;7;8;3;4;9;3];
r1 = [5;1;9;3];
r2 = [6;4];
r = [r1; r2];
ml = logical(prod(bsxfun(@ne, r', m),2));
mm = m(ml);
The bsxfun call creates matrices out of ‘r'’ (note transpose) and ‘m’ that are now the same size, then does element-by-element ‘not equal’ operations on them. This creates a logical matrix of (length(m) x length(r)). The prod call then treats the logical values as numeric, multiplies them row-wise to create a column vector with 1 values where the condition is met. It then converts this back to a logical vector to create ‘mm’. The setdiff function would not work here because you want repeated elements, and setdiff does not offer that option. This code does.
EDIT — You changed the question adding ‘r1’ and ‘r2’ (originally just ‘r’) while I was answering this. I updated my answer to reflect that. (The essential code didn’t change.)
6 个评论
Star Strider
2014-11-11
I’m not quite certain what your data are, but this works when I test it, with ‘r1’ and ‘r2’ now cell arrays:
r1 = {5;1;9;3};
r2 = {6;4};
r = [r1{:} r2{:}];
ml = logical(prod(double(bsxfun(@ne, r, m)),2));
mm = m(ml);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!