Search code examples
matlabsearchvectorcell-array

Searching a cell array of vectors and returning indices


I have a 3000x1 cell array of vectors of different lengths and am looking for a way to search them all for a number and return the cell indices for the first and last occurrence of that number.

So my data looks like this:

[1]
[1 2]
[1 2]
[3]
[6 7 8 9]
etc

And I want to my results to look like this when I search for the number 1:

ans = 1   3

All the indices (e.g. [1 2 3] for 1) would also work, though the above would be better. So far I'm unable to solve either problem.

I've tried

cellfun(@(x) x==1, positions, 'UniformOutput', 0)

This returns a logical array, effectively putting me back at square 1. I've tried using find(cellfun...) but this gives the error undefined function 'find' for input arguments of type 'cell'. Most of the help I can find is for searching for strings within a cell array. Do I need to convert all my vectors to strings for this to work?


Solution

  • C = {[1]
    [1 2]
    [1 2]
    [3]
    [6 7 8 9]}; %// example data
    
    N = 1; %// sought number
    
    ind = cellfun(@(v) any(v==N), C); %// gives 1 for cells which contain N
    first = find(ind,1);
    last = find(ind,1,'last');
    result = [ first last ];