Search code examples
matlabmatrixcell-arraymatrix-indexing

removing rows from matrix based on cell array value


I have 2 cell arrays and one matrix. The first cell array called 'all_ids' is a 6650 x 1 cell which contains strings. The second cell array called 'needed_ids' is a subset of 'all_ids' and is 6600 x 1 cell which also contain strings.

The matrix called 'sales_num' is a 6650 x 500 matrix of doubles, the rows in here are related to the rows 'all_ids'. What I want to do is remove some of the rows from 'sales_num'. The rows I want to remove are the rows that are in 'all_ids' but not in 'needed_ids'. Please see example below.

                                                    Result I'm looking for
all_ids      sales_num           needed_ids         sales_num (now altered)
abc1         1                   abc1               1
def1         2                   def1               2
ghi1         7                   jkl1               8
jkl1         8                   mno1               4
mno1         4                   stu1               2
pqr1         12
stu1         2
vwx1         5

Solution

  • Use setdiff -

    [~,row_ind] = setdiff(all_ids,needed_ids) %// Find rows exclusive to all_ids
    sales_num(row_ind,:)=[]; %// Remove rows that match the exclusiveness