필터 지우기
필터 지우기

How to remove some arrays in a matrix

조회 수: 1 (최근 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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by