I recently came to a problem that I was supposed to define a function with uncertain number of inputs, that is, the number of inputs may vary depending on the practical context. Should I take use of a 2-D array or something else? I don’t know if struct2cell helps and how if it really works.
Does anyone have an idea of the best way to go about doing this?
I’ve probably not been very clear, so please let me know if anything needs clarifying.
Thanks
There are several ways to go about this:
Use optional input arguments if a given parameter means the same regardless of context, but if in some scenarios, additional input is needed.
You can call this function as
out = myFun(1,[],2,3), i.e. pass an empty array for non-needed inputs.If two inputs mean that the function is used one way, and three inputs mean that the function is used in another way (and even the inputs mean different things), use VARARGIN
Finally, you can also have your inputs passed as parameterName/parameterValue pairs. See for example this question on how to handle such input.