Symbolic variables - how to force Matlab to substitute it with real value
38 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Magdalena Mikolajczyk
am 2 Jul. 2016
Kommentiert: Star Strider
am 3 Jul. 2016
Hello,
I have a slight problem with my work and I was hoping maybe someone knows some easy solution I do not (I'm not a pro with Matlab:))
I am calculating symbolic variables (gradient, to be precise) through function and returning it to my main program. The equation has variables: z1, z2 and theta, which are all numeric values inside my main program. But I have no idea how to make Matlab substitute symbolic with real values. I tried to just copy the symbolic equation I got into the program, but it is really complicated and long and it slows my Matlab to the point it don't want to work properly (is it possible? I was over 25 000 characters long).
Is there any command, function, whatever, to just substitute symbolic with real values? It would be like life saver:).
0 Kommentare
Akzeptierte Antwort
Star Strider
am 2 Jul. 2016
Bearbeitet: Star Strider
am 2 Jul. 2016
There are two ways:
1. The subs function will work in all version of the MATLAB Symbolic Math Toolbox;
2. From R2012a onward, you can define symbolic functions. They operate essentially the same way as other MATLAB functions.
Example:
syms t x
y1 = sin(x*t)
y2(x,t) = cos(x*t)
a = 1;
b = [0:0.5:1.5];
y1_out = subs(y1,{x,t},{a,b})
y2_out = y2(a,b)
y1_out =
[ 0, sin(1/2), sin(1), sin(3/2)]
y2_out =
[ 1, cos(1/2), cos(1), cos(3/2)]
Use the vpa function to get floating-point numbers instead of the symbolic expressions:
q1 = vpa(y1_out)
q2 = vpa(y2_out)
q1 =
[ 0, 0.47942553860420300027328793521557, 0.8414709848078965066525023216303, 0.99749498660405443094172337114149]
q2 =
[ 1.0, 0.87758256189037271611628158260383, 0.54030230586813971740093660744298, 0.070737201667702910088189851434269]
See the Symbolic Math Toolbox documentation to learn all the details.
EDIT —
3. If you want to get an executable function from your expression that you can execute in core MATLAB (outside the Symbolic Math Toolbox), use the matlabFunction function:
yfcn = matlabFunction([y1; y2])
yfcn = @(x,t)[sin(t.*x);cos(t.*x)] % Manually Edit To Put It All On One Line
q3 = yfcn(a,b)
q3 =
0 0.47943 0.84147 0.99749
1 0.87758 0.5403 0.070737
Still waking up, or I’d have included that earlier.
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Number Theory finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!