如何为 matlabFunction 生成的函数使用向量参数 [英] How to use a vector argument for a function generated by matlabFunction

查看:41
本文介绍了如何为 matlabFunction 生成的函数使用向量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下 Matlab 代码时:

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

我收到一个错误:

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

我想让 n 向量的代码更通用,在代码中确定 n.
因此,我无法列出所有 n 个变量,例如 f(x(1), x(2), ..., x(n))
有没有办法将 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{:})

重复上面的代码,并使用我定义的内容,这就是我得到的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆