Call function with various number of parameters in Matlab

I am using a symbolic toolbox to create a matlab function. But the number of input data into the generated function varies depending on the number of objects I need (for example, the number of switches). For 2 and 3 switches, the generated function looks like this:

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

In a script using this function, I set the vectors of these parameters:

 a = [a1 a2 ...] 

I want to either call the generated function directly, or make a wrapper function, so I donโ€™t need to change the call statement when I change the number of switches. To complicate this problem, these variables are ACADO variables. This means that matrix and elemental operations are not allowed (i.e., the entire mathematical operation must be performed with scalars, and the equations in the symbolic toolbar must be written for scalars).

+6
source share
2 answers

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

 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 a different number of parameters "transparently" as follows

 fun(v2{:}) number of parameters: 4 fun(v3{:}) number of parameters: 6 
+11
source

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 
+2
source

Source: https://habr.com/ru/post/927006/


All Articles