3

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?

John
  • 63
  • 2
  • 4

2 Answers2

4

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.

Jonas
  • 74,690
  • 10
  • 137
  • 177
0

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{:})
quazgar
  • 4,304
  • 2
  • 29
  • 41