John
John

Reputation: 63

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 myfun(S.x1,S.x2,...). How do I do this?

Upvotes: 3

Views: 6326

Answers (2)

quazgar
quazgar

Reputation: 4630

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

Upvotes: 0

Jonas
Jonas

Reputation: 74940

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.

Upvotes: 4

Related Questions