TimeIsNear
TimeIsNear

Reputation: 755

How to exclude from matrix items of a list?

I have a matrix with multiple rows, and I want to remove some rows of matrix, including the name of the first column belong to a banned list should be ignored.

Like this:

Product name     number      color
P1                x            red
P1                x            blue
p1                x            blue
p2                x            red
p3                x            red
p4                x            red
p4                x            green

listItemToExclude = ['p1', 'p4']

I need to get this result:

Product name     number      color

p2                x            red
p3                x            red

Thanks for your help

Upvotes: 1

Views: 66

Answers (1)

chappjc
chappjc

Reputation: 30589

Say your matrix is a cell array:

M = {'P1', 'x', 'red'; 'P1', 'x', 'blue'; 'p1', 'x', 'blue'; ...
     'p2', 'x', 'red'; 'p3', 'x', 'red'; 'p4', 'x', 'red'; 'p4', 'x', 'green'};

You can pick out the desired rows with ismember:

>> rowsOut = M(ismember(M(:,1),{'p2','p3'}),:)
rowsOut = 
    'p2'    'x'    'red'
    'p3'    'x'    'red'

Or you can use strcmpi with cellfun to ignore case:

keyMatchFun = @(x) strcmpi(M(:,1),x);
keyMatchMasks = cellfun(keyMatchFun,{'p2','p3'},'uni',false);
rowsOut = M(any([keyMatchMasks{:}],2),:)

To add the header:

>> header = {'Product name','number','color'};
>> [header; outRows]
ans = 
    'Product name'    'number'    'color'
    'p2'              'x'         'red'  
    'p3'              'x'         'red'  

EDIT: If you are starting with an exclude list, like listItemToExclude = {'p1', 'p4'};, you can get the list to include (ignoring case) via:

uniqueProducts = unique(lower(M(:,1)));
excludeMasks = cellfun(@(x)strcmpi(uniqueProducts,x),listItemToExclude,'uni',0);
listItemToInclude = uniqueProducts(~any([excludeMasks{:}],2))' %' use above
listItemToInclude = 
    'p2'    'p3'

Upvotes: 2

Related Questions