# How to remove some arrays in a matrix

1 view (last 30 days)
Moe on 10 Nov 2014
Commented: Star Strider on 11 Nov 2014
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 on 10 Nov 2014
Edited: Star Strider on 10 Nov 2014
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.)
Star Strider on 11 Nov 2014
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);

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by