Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] gives same result)

then:

func(a)

gives me:

??? Error ==> func at 11 Not enough input arguments.

Line 11 in func.m is:

error(nargchk(5, 6, nargin));

I notice that this works perfectly:

func(a(1),a(2),a(3),a(4),a(5))

How can I use the vector 'a' as a parameter to a function? I have another function otherfunc(b) which returns a, and would like to use its output as a paramater like this func(otherfunc(b)).

like image 969
Tombola Avatar asked Feb 25 '13 20:02

Tombola


3 Answers

Comma-seperated lists (CSL) can be passed to functions as parameter list,

so what you need is a CSL as 1,2,3,4,5 constructed from an array.

It can be generated using cell array like this:

a=[1,2,3,4,5];
c = num2cell(a);
func(c{:});
like image 93
misssprite Avatar answered Sep 29 '22 03:09

misssprite


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

like image 32
Dedek Mraz Avatar answered Sep 29 '22 03:09

Dedek Mraz


Another method would be to create a separate inline function. Say you have a function f which takes multiple parameters:

f = f(x1,x2,x3)

You can call this with an array of parameter values by defining a separate function g:

g = @(x) f(x(1),x(2),x(3))

Now, if you have a vector of parameters values v = [1,2,3], you will be able to call f(v(1),v(2),v(3)) using g(v).

like image 38
Talfan Evans Avatar answered Sep 29 '22 02:09

Talfan Evans