Search code examples
matlabmatrixindexingcell-array

index of end in array


How can I know the index of last item in cell array? e.g. I'd like to add an item to end of an cell array so I use

    a{1}(1,end+1) = 1

now I'd like to know what is the index equivalent to "end+1" in that statement?

any help is appreciated.


Solution

  • end simply stand for the size of the variable at the corresponding dimension

    whatIsEnd = size( a{1}, 2 ); %// size along second dim
    

    Therefore, end+1 is whatIsEnd+1.

    If cell-array a has many elements and you wish to know the end of each and every one of them, you may consider using cellfun:

    whatIsEnd = cellfun( @(x) size(x,2), a );
    

    Important Note:
    You are adding an element after the end of an array (location end+1). While this code works fine, it is not advisable, as you are changing the array size and this might incur performance depredation if not done with care.
    You can read more about changing size of matlab arrays and pre-allocation in this thread