0

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

I have the following code of what I would like to do.

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

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', 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?

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

DaveNine
  • 391
  • 4
  • 21

1 Answers1

0

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
DaveNine
  • 391
  • 4
  • 21