使用向量作为MatlabFunction的输入 [英] Using vectors as inputs to matlabFunctions

查看:1227
本文介绍了使用向量作为MatlabFunction的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数接受n个变量的功能,foo作为字符串,在点x处求值.

I'd like to create a function that takes in a function of n variables, foo as a string, evaluated at a point x.

我要执行以下操作.

function c = test(foo,n,x)

X=sym('x',[1,n]);
h(X(1:n)) = eval(foo);
H=matlabFunction(h);

A=num2str(x(1));
for i = 2:n
    A=[A,',',' ',num2str(x(i));
end

c = H(eval(A));

end

这里的问题是,matlabFunction H仅将输入作为每个参数,并以逗号分隔.但是,它将x视为单个输入向量,因此返回错误.例如,如果我使用

The problem here is that the matlabFunction H will only take inputs as each argument seperated by a comma. It treats x, however, as a single input vector, and thus returns an error. For example, if I use

foo = 'X(1).^2 + X(2).^2',当n = 2,x = [1,1]时,将无法分辨H([1,1])和H(1,1)之间的区别...因此错误.当然,使用n = 2修复很容易,但是如果我要为函数使用任意数量的变量怎么办?

foo = 'X(1).^2 + X(2).^2', with n=2, x=[1,1], it won't be able to tell the difference between H([1,1]) and H(1,1)...hence the error. Of course it's easy to fix with n=2, but what if I were to have any number of variables for my function?

我希望这是有道理的,谢谢您的帮助. -DS

I hope this makes sense, thanks for any help. -DS

推荐答案

我知道了,这里有一个函数可以执行所要求的操作.

I figured it out, here's a function that will do what is being asked.

%takes a function f as a string, in terms of X(1),X(2),..X(n)
%for example f = ('X(1).^2+X(2).^2+X(3).^2' is a function of 3 variables.
%n is the number of variables of f
%x is the desired vector to evaluate at.

function c = test(foo,n,x)
X = sym('x',[1,n]);
h(X(1:n)) = eval(foo);
H = matlabFunction(h);
args=num2cell(x);
c = H(args{:});
end

这篇关于使用向量作为MatlabFunction的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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