How to use a vector argument for a function genera

2020-02-01 17:08发布

问题:

When I run the following Matlab code:

x=sym('x',[2 1])    
func=x.'*x    
f=matlabFunction(func)    
x=rand(2,1)    
f(x(1),x(2))     % this works    
f(x)             % but this gives an error

I get an error:

Error using symengine>makeFhandle/@(x1,x2)x1.^2+x2.^2
Not enough input arguments.

I want to make the code more general for an n-vector, with n determined in the code.
Therefore I cannot list all n variables like f(x(1), x(2), ..., x(n))
Is there a way to convert the n-vector into a list of n components to be passed to the function?

回答1:

There's a trick you can use with num2cell. What you would do is convert each parameter into its own individual cell, then use the : to deal out the parameters. In other words, you would do this:

x = rand(2,1);
c = num2cell(x);
f(c{:})

Repeating your code above, and using what I have defined, this is what I get:

%// Your code
x=sym('x',[2 1]);    
func=x.'*x;    
f=matlabFunction(func);    
x=rand(2,1);

%// My code
c = num2cell(x);

%// Display what x is
x

%// Display what the output is
out = f(c{:})

I am also displaying what x is and what the final answer is. This is what I get:

x =

    0.1270
    0.9134

out =

    0.8504

This is also the same as:

out = f(x(1), x(2))

out =

    0.8504

In general, you can do this with any dimensional vector you want, provided that your function you're defining can handle that many inputs / dimensions.



回答2:

To solve this, use the vars parameter:

f=matlabFunction(func,'vars',{x})
p=rand(2,1)
f(p)