2014-05-05 66 views
0

我想創建一個函數,它接受一個函數n個變量,foo作爲一個字符串,在點x評估。使用矢量作爲matlab函數的輸入

我有我想要做的以下代碼。

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視爲單個輸入向量,從而返回錯誤。例如,如果我使用

foo = 'X(1).^2 + X(2).^2',其中n = 2,x = [1,1],它將無法辨別H([1,1])和H(1,1)之間的差異)...因此錯誤。當然,使用n = 2很容易解決,但如果我的函數有多個變量,該怎麼辦?

我希望這是有道理的,謝謝你的幫助。 -DS

回答

0

我想通了,這裏有一個函數可以完成要求的內容。

%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