7

I am using symbolic toolbox to generate a matlab function. But the number of input to the generated function is varying with the number of objects that I need (e.g., number of switches). For 2 and 3 switches the generated function look likes this :

y = fun(a1,a2,b1,b2)
y = fun(a1,a2,a3,b1,b2,b3)

In the script using this function I establish vectors of these parameters:

a = [a1 a2 ...]

What I want is to either call the generated function directly or make a wrapper function, so that I do not need to change the call statement when I change the number of switches. To complicate this problem even more, these variables are ACADO variables. That means that matrix and element-wise operation is not allowed (i.e., all math operation must be done with scalars, and equations in symbolic toolbox must be written for scalars).

angainor
  • 11,760
  • 2
  • 36
  • 56
Torstein I. Bø
  • 1,359
  • 4
  • 14
  • 33

2 Answers2

12

You probably look for cell arrays and the {:} operator. It changes the contents of the cell to a coma separated list. The result can be passed to a function as parameters. For example:

v2 = {a1, a2, b1, b2};
v3 = {a1, a2, a3, b1, b2, b3};

And an example function:

function fun(varargin)
    display(['number of parameters: ' num2str(nargin)]);

You can call the function for different number of parameters 'transparently' as follows

fun(v2{:})
number of parameters: 4

fun(v3{:})
number of parameters: 6
angainor
  • 11,760
  • 2
  • 36
  • 56
2

You can create functions with variable numbers of input arguments with varargin.

function fun(varargin)
a = cell2mat(varargin); % works only if arguments indeed only consists of scalars.

% your code comes hereafter
H.Muster
  • 9,297
  • 1
  • 35
  • 46
  • 1
    I do not think that solves my question, because I can not make the function with varying number of parameters, since it is generated by symbolic toolbox (http://www.mathworks.se/help/symbolic/matlabfunction.html) I tried to use vargin but I can't make it work: f = @(x,y) (x+y); vargin{1} = 1; vargin{2} = 2; f(vargin) – Torstein I. Bø Oct 05 '12 at 08:28
  • 1
    The answer provided by @angainor is probably the way you should go. – H.Muster Oct 05 '12 at 09:27