Using string to declare function variables

1 visualización (últimos 30 días)
Josh McCaffrey
Josh McCaffrey el 30 de Mzo. de 2015
Editada: Josh McCaffrey el 30 de Mzo. de 2015
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 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 30 de Mzo. de 2015
Post your code
Josh McCaffrey
Josh McCaffrey el 30 de Mzo. de 2015
Editada: Josh McCaffrey el 30 de Mzo. de 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);

Iniciar sesión para comentar.

Respuestas (1)

Stephen23
Stephen23 el 30 de Mzo. de 2015
Editada: Stephen23 el 30 de Mzo. de 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 comentario
Josh McCaffrey
Josh McCaffrey el 30 de Mzo. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by