how to find out the index of a cell array that cell contains my substring?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Rui Zhang
am 15 Feb. 2024
Kommentiert: Rui Zhang
am 16 Feb. 2024
My question is:
myCellArray = {'John','Mike','foo'};
substring = 'Jo'
Since myCellArray{1} contains "Jo', I expected the index = 1.
How to use cellfun to find the index of the element(s) in the cell array?
2 Kommentare
Akzeptierte Antwort
Fangjun Jiang
am 15 Feb. 2024
Do you have to use cellfun()?
myCellArray = {'John','Mike','foo'};
substring = 'Jo'
find(contains(myCellArray,substring))
7 Kommentare
Voss
am 15 Feb. 2024
myCellArray = {[],'John','','Mike','foo'};
substring = 'Jo';
% replace non-char entries with empty chars:
fixedCellArray = myCellArray;
fixedCellArray(~cellfun(@ischar,fixedCellArray)) = {''};
myIndex = find(contains(fixedCellArray,substring))
Weitere Antworten (1)
Aquatris
am 15 Feb. 2024
Bearbeitet: Aquatris
am 15 Feb. 2024
myCellArray = {'John','Mike','foo','Jonathan','Stuart','Martha','Jo'};
substring = 'Jo';
idx = find(cellfun(@(x) contains(x,substring),myCellArray,'UniformOutput',true))
myCellArray(idx)
4 Kommentare
Aquatris
am 15 Feb. 2024
Bearbeitet: Aquatris
am 16 Feb. 2024
Not the cleaness solution but I think you are looking for something like this then:
myCellArray = {[] 'John','Mike',[],'foo','Johanna','Mark',[];...
0 10 11 20 30 40 50 60;...
1 12 13 22 60 70 80 20;...
2 14 15 18 40 20 10 20;...
3 15 20 25 30 40 50 60};
substring = 'Jo';
idx_empty = cellfun(@isempty,myCellArray(1,:)); % find empty cells in first row
myCellArray_Modified = myCellArray(1,:); % create replica of first row of myCellArray
myCellArray_Modified(idx_empty) = {-1}; % replace empty cells with -1 double
idx = find(cellfun(@(x) contains(string(x),substring),myCellArray_Modified(1,:),'UniformOutput',true));
idx % idx is the column numbers of interest
myCellArray(:,idx)
Siehe auch
Kategorien
Mehr zu Matrix Indexing 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!