Want to use a vector as parameter to a function, without having to separate its elements

前端 未结 7 688
猫巷女王i
猫巷女王i 2021-01-03 04:35

If I call a matlab function with: func(1,2,3,4,5) it works perfectly.

But if I do: a=[1,2,3,4,5] %(a[1;2;3;4;5

7条回答
  •  醉梦人生
    2021-01-03 04:52

    Maybe you could try with nargin - a variable in a function that has the value of the number of input arguments. Since you have a need for different length input, I believe this can best be handled with varargin, which can be set as the last input variable and will then group together all the extra input arguments..

    function result = func(varargin)
        if nargin == 5: % this is every element separately
            x1 = varargin{1}
            x2 = varargin{2}
            x3 = varargin{3}
            x4 = varargin{4}
            x5 = varargin{5}
        else if nargin == 1: % and one vectorized input
            [x1 x2 x3 x4 x5] = varargin{1}
    

    I've written x1...x5 for your input variables

提交回复
热议问题