简体   繁体   中英

How to use a vector argument for a function generated by matlabFunction

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?

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.

To solve this, use the vars parameter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM