[英]In Matlab, for a multiple input function, how to use a single input as multiple inputs?
I have a function that takes a variable number of inputs, say myfun(x1,x2,x3,...)
. 我有一个函数,它接受可变数量的输入,比如
myfun(x1,x2,x3,...)
。
Now if I have the inputs stored in a structure array S, I want to do something like myfun(S.x1,S.x2,...)
. 现在如果我将输入存储在结构数组S中,我想做像
myfun(S.x1,S.x2,...)
这样的事情。 How do I do this? 我该怎么做呢?
You can first convert your structure to a cell array using STRUCT2CELL , and then use that to generate the list of multiple inputs. 您可以先使用STRUCT2CELL将结构转换为单元格数组,然后使用它来生成多个输入的列表。
S = struct('x1','something','x2','something else');
C = struct2cell(S);
myfun(C{:});
Note that the order in which the fields in S
are defined are the order in which the inputs are passed. 请注意,定义
S
中字段的顺序是输入的传递顺序。 To check that the fields are in the proper order, you can run fieldnames
on S
, which returns a cell with field names corresponding to the values in C
. 要检查字段的顺序是否正确,可以在
S
上运行fieldnames
,该字段名返回一个字段名称与C
的值对应的单元格。
Something to add to Jonas' answer: Actually you can omit the struct and go right for the cell which is then expanded into a list for the function arguments: 要添加到Jonas的答案中的东西:实际上你可以省略结构并向右移动单元格,然后将其扩展为函数参数的列表:
c = {125, 3};
nthroot(c{:})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.