MATLAB - find multidimensional indices of entries located in nested cell array

Viewed 50

In MATLAB, say I have a cell array as follows:

cell_arr = {{'a', 'b', 'c'}, {'d', 'e', 'f', 'g', 'h'}, {'a', 'b', 'c'}};

I want a way to find all locations in the cell array where e.g., 'a' occurs. So something like

where(cell_arr, 'a'); % returns e.g., [[1 1] ; [3 1]]

How can I do this?

Thanks for any help.

1 Answers

This solution may not be simple but it will work. Basically, just loop through each cell in the multidimensional cell array and find the location of the word:

function location = where(cell_arr, word)

% initialize location
location = zeros(sum(char([cell_arr{:}]) == word),2);

% loop through cell_arr to find the location
count = 0;
for i = 1:length(cell_arr)
    for j = 1:length(cell_arr{i})
        if cell_arr{i}{j} == word
            count = count + 1;
            location(count,:) = [i j];
        end
    end
end
end

Example

where(cell_arr, 'a')

Output:

ans =
     1     1
     3     1
Related