How to remove a whole row of data?

1 次查看(过去 30 天)
Sandy
Sandy 2016-8-15
编辑: Guillaume 2016-8-16
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 个评论
Guillaume
Guillaume 2016-8-15
编辑:Guillaume 2016-8-15
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?

请先登录,再进行评论。

回答(2 个)

KSSV
KSSV 2016-8-16
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 个评论
Guillaume
Guillaume 2016-8-16
编辑:Guillaume 2016-8-16
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)), :) = []

请先登录,再进行评论。


Guillaume
Guillaume 2016-8-16
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), :) = []

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by