Search code examples
matlabcell-arrayfunction-call

Cell elements as comma separated input arguments for varargin function


Imagine a function with a variable number of input arguments, alternately asking for a string and a value.

myfunction('string1',value1,'string2',value2,...)

e.g.

myfunction('A',5,'B',10)

I want to keep the ability to call the function like that and I dont want to change the evaluation of varargin inside the function. (Except ('string1','string2',...,value1,value2,...) if that helps)

But I also have my input strings and values stored in a cell array inputvar <4x1 cell>:

inputvar = 

'A'    [5]    'B'    [10]

Also this cell array has a variable length.

My intention is to call my function somehow as follows:

myfunction( inputvar )

which is obviously not working. Any ideas how I could transform my cell to a valid input syntax?


I already tried to generate a string like

''string1',value1,'string2',value2'

and use eval to use it in the function call. But it didn't worked out. So alternatively is there a way to transfor a string to code?


Solution

  • You should be able to do it like this:

    myfunction(inputvar{:})
    

    {:} creates a comma separated list


    EDIT: For example:

    function val = myfunction(string1,value1,string2,value2)
        if string1 == 'A'
          val = value1;
        else
          val = value2;
    end
    
    myfunction('A',5,'B',10)
    myfunction('B',5,'B',10)
    A = {'A',5,'B',10};
    myfunction(A{:})
    A = {'B',5,'B',10};
    myfunction(A{:})
    

    returns:

    ans =  5
    ans =  10
    ans =  5
    ans =  10