How to remove some arrays in a matrix

4 ビュー (過去 30 日間)
Moe
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 件のコメント
Moe
Moe 2014 年 11 月 11 日
Hi Star,
Matrix r1 and r2 will be updated in each iteration in my code. So, I'm trying to use a cell array for ml and mm as follows:
r{j} = [r1{j}; r2{j}];
ml{j} = logical(prod(double(bsxfun(@ne, r{j}', m),2));
mm{j} = m(ml{j});
But, it gives the following error:
Error using bsxfun
Operands must be numeric arrays.
Can you please help me?
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 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by