# Find in a cell array?

2,622 views (last 30 days)
M G on 7 Aug 2013
Commented: Kylie Hansen on 16 Aug 2017
Hello all,
Suppose a cell array 10x1 consisted of random numbers from 1 to 5. How can I find the locations for number 5?
All the best,
MhD

Jan on 7 Aug 2013
I've deleted the duplicate question.
Elias Berra on 17 Nov 2015
X = my_array_data [row,col] = find(X==21) %In this example, it retrieves the cell location which contains the value 21.

Jan on 7 Aug 2013
Edited: Jan on 7 Aug 2013
C = {1,5,3,4,2,3,4,5,2,1};
index = find([C{:}] == 5);
Here [C{:}] is a faster inlined version of cell2mat.
Alternative:
index = cellfun(@(x) x==5, C, 'UniformOutput', 1);
Or the long and most likely faster form:
index = false(1, numel(C))
for k = 1:numel(C)
index(k) = (C{k} == 5);
end
[EDITED] If you are talking of a cell string, this is much faster:
D = {'1' '5' '3' '4' '2' '3' '4' '5' '2' '1'};
index = find(strcmp(D, '5'));

M G on 8 Aug 2013
strcmp works! Thanks. Here is data:
Here is how it worked based on what you suggested.
Index = [];
j=1;
for i=1:size(S,1)
if(strcmp(S(i,:),' -88 ')==1)
Index(j) = i;
j = j+1;
end
end
Jan on 8 Aug 2013
This looks strange. When eheader is numerical, converting it elementwise inside a cellfun call to a string and afterwards by char to a char matrix is cruel. Then assuming a certain number of spaces around the value is fragile, because the width depends on the values. What about this (I cannot open the posted MAT file, better post code in the forum which creates the example data):
STRCMP works much faster with cell strings, so at least do not let CHAR() create a CHAR-matrix.
Kylie Hansen on 16 Aug 2017
Just a casual MATLAB coder dropping by this older thread on a hunt for answers. Your response for the cell string method worked easily for me. Thank you so much for including it!

Caroline on 7 Aug 2013
Edited: Azzi Abdelmalek on 7 Aug 2013
cellarray_new = zeros; %initializing the array
ind = 1; %indices for new array
for j = 1:10
if (cellarray(j) == 5)
cellarray_new(ind) = j;
ind = ind + 1;
end
end
the array cellarray_new will contain all the indices of the original cell array that contain the number 5