How to remove some arrays in a matrix

2 ビュー (過去 30 日間)
Moe 2014 年 11 月 10 日
コメント済み: Star Strider 2014 年 11 月 11 日
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];


Star Strider
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
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 件)

Community Treasure Hunt

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

Start Hunting!

Translated by