Want to use a vector as a parameter for a function without separating its elements

If I call matlab function with:   FUNC (1,2,3,4,5) it works fine.

But if I do this:   a = [1,2,3,4,5] % (a [1; 2; 3; 4; 5] gives the same result)

then

FUNC (a)

gives me:

??? Error ==> func at 11 There are not enough input arguments.

Line 11 in func.m:

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

I notice this works fine:

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

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

+5
7

, (CSL) ,

CSL 1,2,3,4,5, .

:

a=[1,2,3,4,5];
c = num2cell(a);
func(c{:});
+5

, nargin - , . , , varargin, .

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}

x1...x5

+3

- . , f, :

f = f(x1,x2,x3)

, g:

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

, v = [1,2,3], f (v (1), v (2), v (3)), g (v).

+1

.

function result = func(a)
    if ~isvector(a)
        error('Input must be a vector')
    end
end
0

Matlab vectoes ( ), .
func 5 , , Matlab , . Matlab , 5-?

,

s.type = '()';
s.subs = {1:5};
func( subsref( num2cell( otherfunc(b) ), s ) )

, ( MATLAB), 5- a ( otherfunc(b)) , 5 func.
, a{:} a(:) subsref.

0

You can create a function of the following form:

function [ out ] = funeval( f, x )
   string = 'f(';
   for I = 1:length(x)
      string = strcat( string, 'x(' , num2str(I), '),' );
   end
   string( end ) = ')';
   out = eval( string );
end

In this case, funeval( func, a )it gives the desired result.

0
source

Use eval:

astr = [];
for i=1:length(a)
    astr     = [astr,'a(',num2str(i),'),']; % a(1),a(2),...
end
astr  = astr(1:end-1);
eval(['func(' astr ');']);
0
source

All Articles