Number to string variable

2 次查看(过去 30 天)
Nuno
Nuno 2015-5-7
Hello everyone!
I have:
z1=12;
eq='(z-z1)^2';
Is it possible put value z1 into the eq variable (string)?
Thanks

回答(1 个)

Star Strider
Star Strider 2015-5-7
It is if you have the Symbolic Math Toolbox:
syms z
z1=12;
eq= (z-z1)^2;
eq = subs(eq)
produces:
eq =
(z - 12)^2
  3 个评论
Nuno
Nuno 2015-5-7
编辑:Nuno 2015-5-7
but the variable eq is not a string
Star Strider
Star Strider 2015-5-7
编辑:Star Strider 2015-5-7

Actually, they’re not strings but symbolic expressions.

This is how I would do it:

syms x y z r
x1=169;
x2=169;
y1=200;
y2=178;
z1=202;
z2=196;
x3=169;
x4=169;
y3=198;
y4=180;
z3=204;
z4=198;
equ1=subs((x-x1)^2+(y-y1)^2+(z-z1)^2-r^2);
equ2=subs((x-x2)^2+(y-y2)^2+(z-z2)^2-r^2);
equ3=subs((x-x3)^2+(y-y3)^2+(z-z3)^2-r^2);
equ4=subs((x-x4)^2+(y-y4)^2+(z-z3)^2-r^2);
[x,y,z,r]=solve([equ1,equ2,equ3,equ4], [x,y,z,r])

The substitutions are correct, but the problem is that the solutions are empty symbolic variables. There seems to be no analytic solution to the system.

You might want to give it a go with fsolve:

x1=169;
x2=169;
y1=200;
y2=178;
z1=202;
z2=196;
x3=169;
x4=169;
y3=198;
y4=180;
z3=204;
z4=198;
equ = @(b) [(b(1)-x1).^2+(b(2)-y1).^2+(b(3)-z1).^2-b(4).^2;
            (b(1)-x2).^2+(b(2)-y2).^2+(b(3)-z2).^2-b(4).^2;
            (b(1)-x3).^2+(b(2)-y3).^2+(b(3)-z3).^2-b(4).^2;
            (b(1)-x4).^2+(b(2)-y4).^2+(b(3)-z4).^2-b(4).^2];
B = fsolve(equ, randi([80 120], 4, 1))

produces (with one set of initial estimates for [x,y,z,r]):

B =
     303.8357
     199.3227
     135.3456
     150.2771

It stops after 400 iterations because it is still searching for a solution, so experiment with the options structure and other fsolve variations if necessary to give the best parameter estimates and information about the solution.

EDIT —

If you want to print the equations out as strings, use this (or something like it):

x1=169;
y1=200;
z1=202;
equstr ='(x-%.0f)^2+(y-%.0f)^2+(z-%.0f)^2-r^2';         % Produces String For ‘equ’
fprintf(1, [equstr '\n'], x1, y1, z1)

that produces:

(x-169)^2+(y-200)^2+(z-202)^2-r^2

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by