Cell elements as comma separated input arguments for varargin function

余生长醉 提交于 2019-12-01 20:41:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/19275212/cell-elements-as-comma-separated-input-arguments-for-varargin-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!