How to remove a whole row of data?

1 view (last 30 days)
Sandy
Sandy on 15 Aug 2016
Edited: Guillaume on 16 Aug 2016
I have a column of data, A. I have a data matrix, X. I want to go through column A and see if each one of the entries in column A is found anywhere in matrix X. If it is, I want to remove the whole row where that entry is found. For example:
A =
SAH
SAE
X =
2 BAH CAE
4 LER MFH
5 PER SAE
3 KEI PEL
5 SAH LOH
7 SLE POE
Once I remove the rows, I would end up with something like:
X =
2 BAH CAE
4 LER MFH
3 KEI PEL
7 SLE POE
  1 Comment
Guillaume
Guillaume on 15 Aug 2016
Edited: Guillaume on 15 Aug 2016
It would be great if you used valid matlab syntax for your examples, so we didn't have to ask:
What are A and X?
  • char matrices? i.e.:
A = ['SAH';'SAE']
X = ['2 BAH CAE'; '4 LER MFH'; ...]
  • cell arrays of strings?
A = {'SAH'; 'SAE'}
X = {'2', 'BAH', 'CAE'; '4', 'LER', 'MFH'; ...}
  • something else?

Sign in to comment.

Answers (2)

KSSV
KSSV on 16 Aug 2016
clc; clear all ;
A = [{'SAH'} ;{'SAE'}] ;
X = [{'2'}, {'BAH'}, {'CAE'}
{'4'} {'LER'} {'MFH'}
{'5'} {'PER'} {'SAE'}
{'3'} {'KEI'} {'PEL'}
{'5'} {'SAH'} {'LOH'}
{'7'} {'SLE'} {'POE'}];
idx = strfind(X, A{1}); % comapre the strings of A in X and get indices
idx1 = find(not(cellfun('isempty', idx))); % get global indices
[i,j] = ind2sub(size(X),idx1) ; % get sub indices
X(i,:) = []; % remove the respective row
  1 Comment
Guillaume
Guillaume on 16 Aug 2016
Edited: Guillaume on 16 Aug 2016
Assuming that A and X are indeed cell arrays (see comment to the question), a much simpler way of obtaining the answer is to use ismember.
Note that because you're using strfind, your answer will match 'PER' not only with 'PER', but also with 'PERSON' or 'APERITIF'. This may or may not be an issue for the OP.
Also note that you can get directly rows and columns with find (just give it two outputs|, so you don't need to go through ind2sub:
[i, j] = find(~cellfun('isempty', idx));
In any case, you could just avoid the find altogether and just manipulate the logical array output of the cellfun:
X(any(~cellfun('isempty', idx)), :) = []

Sign in to comment.


Guillaume
Guillaume on 16 Aug 2016
Assuming that A and X are indeed cell arrays (see comment to the question):
A = {'SAH'; 'SAE'}
X = {'2', 'BAH', 'CAE';
'4', 'LER', 'MFH';
'5', 'PER', 'SAE';
'3', 'KEI', 'PEL';
'5', 'SAH', 'LOH';
'7', 'SLE', 'POE'}
X(any(ismember(X, A), 2), :) = []

Categories

Find more on Characters and Strings 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!