How to remove rows from cell array based on multiple conditions?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Calabrese
am 15 Jul. 2017
Kommentiert: Calabrese
am 15 Jul. 2017
I would like to separate the following sample array into 2 arrays. If C contains any of the following strings (red, spoon, fork) within the row, I want to remove the row and put it into a new cell array.
clear all
clc
% Sample cell array
C = [{'A1';'A3';'A4';'A7'},{'blue';'green';'red';'blue'},{'spoon';'fork';'knife';'cup'},num2cell(rand(4,1))];
idx = cellfun(@(x) strcmp(x, 'red', 'spoon','fork'), C(:,:));
% Extracted data
C1 = C(idx,:);
% Others
C2 = C(~idx,:);
new arrays should look like...
C1 =
'A1' 'blue' 'spoon' [0.6948]
'A3' 'green' 'fork' [0.3171]
'A4' 'red' 'knife' [0.9502]
C2 =
'A7' 'blue' 'cup' [0.0344]
0 Kommentare
Akzeptierte Antwort
James Tursa
am 15 Jul. 2017
Bearbeitet: James Tursa
am 15 Jul. 2017
E.g., assuming your columns are nice and are not mixed class:
C = your cell array
S = your cell string compare array, e.g., {'red', 'spoon','fork'}
x = cellfun(@ischar,C);
Cx = reshape(C(x),size(C,1),[]);
y = any(ismember(Cx,S),2);
C1 = C(y,:);
C2 = C(~y,:);
7 Kommentare
James Tursa
am 15 Jul. 2017
OK, since your columns can have mixed data type, I have converted my code to loop over the rows:
m = size(C,1);
y = true(m,1);
for k=1:m
x = cellfun(@ischar,C(k,:));
y(k) = any(ismember(C(k,x),S));
end
C1 = C(y,:);
C2 = C(~y,:);
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!