MATLAB: How to write a function with a number of outputs which is governed by a number of inputs

functionmultiple outputs

I want to create a function which calculates heat capacity (HC) for a number of molecules (let's say 30 different molecules, each has its own HC). But I do not need HC of all 30 molecules each time I call the function, so in the function input I want to specify the desired molecules, for example, h2, co2 and h2o. Then, the function should create three output variables named cp_h2, cp_co2 and cp_h2o which contain values of HC for the corresponding molecules. So I need any suggestions on how to implement this idea. Thank you!

Best Answer

You can easily use varargin and varargout to do this:
function varargout = funname(varargin)
varargout = varargin; % preallocation
for k = 1:numel(varargin)
varargout{k} = ... varargin{k} % your code
end
end
Note that you basically have this choice:
  1. have a loop inside the function (with multiple input and output arguments using varargin/varargout), or
  2. 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:
Related Question