如何使用向量参数由matlabFunction生成的功能 [英] How to use a vector argument for a function generated by matlabFunction
问题描述
当我运行下面Matlab的code:
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.
我想使code为正向量比较一般,其中n在code确定。结果
因此,我不能列出像所有的n变量函数f(x(1),X(2),...,X(N))
结果
有没有一种方式向正转化载体为n个组件列表被传递给函数?
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?
推荐答案
有是您可以使用的 num2cell
。你会做什么是对每个参数转换成自己独立的单元格,然后使用:
来处理出的参数。换句话说,你可以这样做:
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{:})
重复您的code以上,并且使用我定义的东西,这是我得到:
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{:})
我也显示了什么 X
终止和最后的答案是什么。这是我得到:
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
这也是一样:
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.
这篇关于如何使用向量参数由matlabFunction生成的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!