Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

matlab - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...