Search code examples
arraysmatlabvectorcell-array

How to find index of the last non-empty element in a cell array


I initialized a very long cell array(vector?)

train_labels = cell(16218, 1);

These will be populated using files from 50 different folders, to make sure that the files are indexed in the right location, I need the index of the last cell array that was written to.

For example after reading one folder, the index in train_labels had reached 5406. Now to read the images from the next folder they must be saved to the next index that is 5407. To make that work I need to find the location of the last non-empty array in train_labels.

Since the simple find(train_labels,1,'last') does not work on cell arrays. I used cellfun but that is also not working. This is what I tried:

cellfun(@find, train_labels, 'last')
Error using cellfun
Input #3 expected to be a cell array, was char instead.

Would appreciate any guidance on how to get the last index of the cell array.

Thank you


Solution

  • Use cellfun with 'isempty' option -

    last_non_empty_index = find(~cellfun('isempty',train_labels),1,'last')
    

    You can also use cellfun(@isempty..), but I believe that must be slower. This has been discussed in detail in this Undocumented MATLAB Blog post.

    isempty is a built-in and as such appears to be an optimized implementation. Other built-ins that are available in 2014A version of cellfun are - 'isreal', 'islogical', 'length', 'ndims', 'prodofsize', 'size', 'isclass'. I am hoping that these are fast implementations as well. More info on these are available in its official documentation that can be accessed with >> help cellfun.