Search code examples
matlabcell

Using cellfun for logical indexing


I have a cell data containing one row and four column. What i am trying to do is to go through elements in first column and see if an year '2018' is seen in the first column of each cell. When i perform this code, it will only give me the indices containing '2018' in the fourth cell. Not all the cells. Any help will be appreciated.

time = cellfun(@x, contains(x,'2018'),data{ii}(:,1))

This is the image of cell <code>data</code>


Solution

  • I have created a small data sample as part of an example which I hope will help you solve the problem.

    %Create cell array of strings.
    data = {["2018","date","2018";"stack","cell2018","fun"],["data","stackoverflow","2018";"array","variable","data2018"]}
    
    %Search for substring 2018 in the first column of every cell.
    time = cellfun(@(x) contains(x(:,1),'2018'),data,'UniformOutput',0)
    

    The output of time is a logical cell array:

    >>time 
    
    {2×1 logical}    {2×1 logical}
    
    >>time{1}
    
    1
    0
    
    >>time{2}
    
    0
    0
    

    For the first cell, the column contains 2018 and stack, therefore 1 and 0 are returned.

    For the second cell, the column contains data and array, therefore 0 and 0 are returned.

    If you wish to find the indexes from the logical array, you can use the find function with outputs [row,col].