开发者

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,...).

Now if I have the inputs stored in a structure array S, I want to do something like my开发者_StackOverflowfun(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.

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. 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.


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:

c = {125, 3};
nthroot(c{:})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜