Calling function with varying number of parameters in Matlab

前端 未结 2 523
甜味超标
甜味超标 2020-12-31 20:21

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

相关标签:
2条回答
  • 2020-12-31 21:04

    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
    
    0 讨论(0)
  • 2020-12-31 21:17

    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
    
    0 讨论(0)
提交回复
热议问题