Brethlosze
Brethlosze

Reputation: 1618

Passing A Variable Number of Arguments into a Function

In Matlab, I have a variable length cell of values:

C={A1,...,An}

How should I pass and distribute these values into a function able to receive a variable number of arguments?

f(A1,...,An)

Ultimately if not possible, how should I modify the beginning of this function for making this work?

Upvotes: 0

Views: 262

Answers (2)

user2305193
user2305193

Reputation: 2059

This is exactly what 'varargin' does for you. Read in multiple variables, e.g. f(a,b,c), and store them in a cell-array.

Then you could go for one of these 'quick and dirty' processing methods:

function asdf(varargin)
  yourarguments=[varargin{:}]; % if all numerical
  yourargumentscontain=contains(varargin,'asdf'); %if strings contained
  all_processed_args=cellfun(@(x) whateveryouwant_function(x), varargin); %for older versions of matlab
end

For more here's documentation: https://ch.mathworks.com/help/matlab/matlab_prog/parse-function-inputs.html

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

You need to convert the cell array into a comma-separated list via curly-brace indexing, that is, use C{:}.

Example with the reshape function:

>> C = {ones(3,4), 2, 2, 3};
>> y = reshape(C{:});
>> size(y) % check
ans =
     2     2     3

Upvotes: 2

Related Questions