functionmatlab

How to pass cell indexing as an input argument to a function, such that cell inside the function can use the indexing directly?


I am wondering if we can pass cell indexing as an input argument to a function, such that a cell inside the function can parse it.

For example, given a cell like x = num2cell(reshape(1:24, [2,3,4])), we can do indexing

>> x(:,1,2)

ans =

  2×1 cell array

    {[7]}
    {[8]}

However, if I want to pass (:,1,2) as an input argument to a custom function (see the attempt below, which is not working for sure), what can we do?

f({:,1,2}) % not working

function y = f(varargin)
x = num2cell(reshape(1:24, [2,3,4]));
y = x(varargin{:});
end

Solution

    1. Because you are using a cell array to input the indices, varargin is a cell array with your cell nested as the first element. You don't need varargin and can simply let f expect a single input which is your indexing cell

    2. You can't pass : around like this, but : and the char ':' will be treated the same when indexing so you can do

    f({':',1,2}) % Note the colon operator is a character
    
    function y = f(idx)
    % Take an indexing array 'idx' and use it to index a subset
    % of the generated array 'x'
    x = num2cell(reshape(1:24, [2,3,4]));
    y = x(idx{:});
    end
    

    Alternatively, if you wanted to use varargin to achieve the same functionality, you could do

    f(':',1,2) % Note the colon operator is a character
    
    function y = f(varargin)
    % Take an indexing array 'idx' and use it to index a subset
    % of the generated array 'x'
    x = num2cell(reshape(1:24, [2,3,4]));
    y = x(varargin{:});
    end
    

    The 2nd option means you don't need to put the indices into a cell array, but would probably be less clear if you had other inputs to f.


    Here is a MathWorks blog post about passing around indices in cell arrays, including a reference to using the colon operator in quotes:

    https://blogs.mathworks.com/loren/2006/11/10/all-about-the-colon-operator/