how to find out the index of a cell array that cell contains my substring?

조회 수: 10 (최근 30일)
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
Rui Zhang
Rui Zhang 2024년 2월 15일
If I don't use cell function, the following code should work:
myCellArray = {'John','Mike','foo'};
substring = 'Jo';
indexForMySubstring = zeros([1,numel(myCellArray)]);
kk = 1;
for ii =1: numel(myCellArray)
if contains(myCellArray{ii},substring)
indexForMySubstring(kk) = ii;
kk = kk+1;
end
end
if kk>1.5
indexForMySubstring = indexForMySubstring(1:kk-1);
else
indexForMySubstring = [];
end
This will return array of the indexes that contains 'Jo' in myCellArray
But this code runs too slow when it is used for a large application.
I am looking for a solution that runs faster than this like using cellfun.

댓글을 달려면 로그인하십시오.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2024년 2월 15일
Do you have to use cellfun()?
myCellArray = {'John','Mike','foo'};
substring = 'Jo'
substring = 'Jo'
find(contains(myCellArray,substring))
ans = 1
  댓글 수: 7
Voss
Voss 2024년 2월 15일
myCellArray = {[],'John','','Mike','foo'};
substring = 'Jo';
% replace non-char entries with empty chars:
fixedCellArray = myCellArray;
fixedCellArray(~cellfun(@ischar,fixedCellArray)) = {''};
myIndex = find(contains(fixedCellArray,substring))
myIndex = 2

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Aquatris
Aquatris 2024년 2월 15일
편집: Aquatris 2024년 2월 15일
Using the @Fangjun Jiang example, how about
myCellArray = {'John','Mike','foo','Jonathan','Stuart','Martha','Jo'};
substring = 'Jo';
idx = find(cellfun(@(x) contains(x,substring),myCellArray,'UniformOutput',true))
idx = 1×3
1 4 7
myCellArray(idx)
ans = 1×3 cell array
{'John'} {'Jonathan'} {'Jo'}
  댓글 수: 4
Aquatris
Aquatris 2024년 2월 15일
편집: Aquatris 2024년 2월 16일
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
idx = 1×2
2 6
myCellArray(:,idx)
ans = 5×2 cell array
{'John'} {'Johanna'} {[ 10]} {[ 40]} {[ 12]} {[ 70]} {[ 14]} {[ 20]} {[ 15]} {[ 40]}

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by