Using string to declare function variables

3 views (last 30 days)
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 Comments
Josh McCaffrey
Josh McCaffrey on 30 Mar 2015
Edited: Josh McCaffrey on 30 Mar 2015
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);

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 30 Mar 2015
Edited: Stephen23 on 30 Mar 2015
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 Comment
Josh McCaffrey
Josh McCaffrey on 30 Mar 2015
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!