Borrar filtros
Borrar filtros

Order terms in symbolic poly converted to string

58 visualizaciones (últimos 30 días)
Ethan Duckworth
Ethan Duckworth el 17 de Jul. de 2024 a las 23:56
Comentada: Ethan Duckworth el 18 de Jul. de 2024 a las 10:55
Is there a way to control the order of the terms in a symbolic polynomial that has been converted to string?
E.g. the following
syms x
T=taylor(exp(x),order=3);
string(T)
results in
ans = "x + x^2/2 + 1"
and I would rather have it as 1+x+x^2/2 or the reverse order. I'll be putting this in the title of a plot so if there is some other way to automatically get the correct order in the title that would work equally as well.

Respuesta aceptada

Liam Ivers
Liam Ivers el 18 de Jul. de 2024 a las 1:13
Editada: Liam Ivers el 18 de Jul. de 2024 a las 1:17
Use the sympref function to change the display of the symbolic polynomial:
I noticed that the string function does not update with this change(A = "x + x^2/2 + 1"), but it does if you use the latex command (B = '1+x+\frac{x^2}{2}') which may look better for plot headings.
syms x
T=taylor(exp(x),order=3)
sympref('PolynomialDisplayStyle','ascend')
A = string(T)
B = latex(T)
titletext = ("$" + latex(T) + '$')
title(titletext,Interpreter='latex')
  2 comentarios
Sam Chak
Sam Chak el 18 de Jul. de 2024 a las 1:36
@Ethan Duckworth, Consider trying this "what-you-see-is-what-you-get" direct approach.
sympref("PolynomialDisplayStyle", "ascend");
syms x
T = taylor(exp(x), order=3)
T = 
titletext = ("$" + latex(T) + '$');
fplot(T), grid on
title(titletext, Interpreter='latex')
Ethan Duckworth
Ethan Duckworth el 18 de Jul. de 2024 a las 10:55
Weird that string(T) doesn't preserve the order of the terms, but that latex(T) does!

Iniciar sesión para comentar.

Más respuestas (1)

James Tursa
James Tursa el 18 de Jul. de 2024 a las 1:26
Editada: James Tursa el 18 de Jul. de 2024 a las 1:50
Brute force if you need the string for some reason?
syms x
ex = taylor(exp(x),order=3)
ex = 
[C,T] = coeffs(ex)
C = 
T = 
terms = fliplr(C.*T)
terms = 
n = numel(terms);
s = char(terms(1));
for k=2:n
c = char(terms(k));
if( c(1)=='-' )
s = [s ' - ' c(2:end)];
else
s = [s ' + ' c];
end
end
s
s = '1 + x + x^2/2'
  1 comentario
Ethan Duckworth
Ethan Duckworth el 18 de Jul. de 2024 a las 10:54
Wholy cow! That works, but the shorter approach by @Liam Ivers is the one I accepted.

Iniciar sesión para comentar.

Categorías

Más información sobre Symbolic Math Toolbox 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