单元格元素用作varargin函数的逗号分隔输入参数 [英] Cell elements as comma separated input arguments for varargin function

查看:51
本文介绍了单元格元素用作varargin函数的逗号分隔输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个具有可变数量输入参数的函数,交替询问一个字符串和一个值.

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

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

例如

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

我想保持像这样调用函数的能力,并且我不想更改函数内部的varargin的求值. (('string1','string2',...,value1,value2,...)除外,

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)

但是我也将输入的字符串和值存储在单元格数组inputvar <4x1 cell>中:

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'

并使用eval在函数调用中使用它.但这没有解决.那么,有没有一种方法可以将字符串转换为代码呢?

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?

推荐答案

您应该可以这样做:

myfunction(inputvar{:})

{:}创建一个逗号分隔列表

例如:

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{:})

返回:

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

这篇关于单元格元素用作varargin函数的逗号分隔输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆