Using string to declare function variables

1 次查看(过去 30 天)
I have a string containing the names of the variables in the function: varlst = 'x1,x2'
I have function fx= 10*(x1 - 3)^2 + (x2 + 5)^2
I want fx(x1,x2) = 10*(x1 - 3)^2 + (x2 + 5)^2
But when I type fx(varlst) I get fx = [ 10*(x1 - 3)^2 + (x2 + 5)^2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10*(x1 - 3)^2 + (x2 + 5)^2, 0, 0, 0, 0, 10*(x1 - 3)^2 + (x2 + 5)^2, 10*(x1 - 3)^2 + (x2 + 5)^2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10*(x1 - 3)^2 + (x2 + 5)^2]
Does anyone have any idea why this is happening and what I can do to get my desired result?
  2 个评论
Josh McCaffrey
Josh McCaffrey 2015-3-30
编辑:Josh McCaffrey 2015-3-30
Here is my code. This is my first time coding with matlab so it might look weird but the idea is to be able to pick out how many variables there are in the user input (x1,x2,...,xn), declare these variables as sym and then perform operations on the function.
c=0; k=[1]; varlst='';
prompt1 = 'Enter function to minimize: '; fxs = '10*(x1-3)^2+(x2+5)^2';
while k ~= 0
c=c+1; num = strcat('x', int2str(c)); k = strfind(fxs, num); if k>0; syms(num); varlst = strcat(varlst, num , ','); end end varlst = varlst(1:end-1); c=c-1;
fx=sym(fxs); fx(varlst)=fx;
fx0d(varlst) = gradient(fx);

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2015-3-30
编辑:Stephen23 2015-3-30
Why not simply use an anonymous function to define this:
>> fx = @(x1,x2) 10*(x1 - 3)^2 + (x2 + 5)^2;
>> fx(1,2)
ans = 89
  1 个评论
Josh McCaffrey
Josh McCaffrey 2015-3-30
The thing is I have no idea how many variables the user will input. I need my code to work for (x1,x2,...,xn). I posted my code into a comment above so you can see it.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by