You can easily use varargin and varargout to do this:
function varargout = funname(varargin)
varargout = varargin;
for k = 1:numel(varargin)
varargout{k} = ...
end
end
Note that you basically have this choice:
- have a loop inside the function (with multiple input and output arguments using varargin/varargout), or
- call the function once for each calculation (with one input and output argument), e.g. in a loop using a cell array.
I would suggest that it would be simpler to write the function to process just one calculation at a time (rather than an arbitrary number), because this has advantages in terms of testability, tab function completion, and the ease of supplying/collecting all of the outputs. Having the function accept and return values for multiple independent calculations like this:
[cp_h2,cp_co2,cp_h2o] = myfun(h2,co2,h2o)
offers no real advantage over calling a simpler function with just one input and output as many times as required:
cp_h2 = myfun(h2);
cp_co2 = myfun(co2);
cp_h2o = myfun(h2o);
, but has the disadvantage that using positional arguments introduces a higher chance of mistakes as they are much less clear than one calculation per line.
Note that if you do decide to process multiple calculations in one function call then accepting and returning the data in one array (ND numeric, cell, struct) would probably be much simpler than providing and returning multiple input and output arguments. In this case you might find that you can vectorize your code as well, which makes it simpler and often more efficient:
You also might like to read this:
Best Answer