Conversion to double from sym is not possible

5 visualizaciones (últimos 30 días)
Erik
Erik el 5 de Oct. de 2014
Comentada: Star Strider el 6 de Oct. de 2014
Hello All. I am trying to plot a comparison between the ode45 solution of a simple spring mass equation and the exact solution. The equation is x''=1-(4pi)^2*x My code is below:
%1) Must rewrite 2nd order equation as a system of 1st order equations
clear all
time_period = [0 4];
[t,x]=ode45(@spring,time_period, [0; 0]);
%Call function spring:
% | function dxdt=spring(t,x) |
% | dxdt=[x(2), 1-(4*pi)^2*x(1)]; |
%2)
plot(t,x(:,1));
title('Spring-Mass Function ODE45 Solution')
ylabel('x-position(m)');
xlabel('time(s)');
%3)
x_exact=dsolve('D2x == 1-(16*pi^2)*x', 'Dx(0)=0', 't');
plot(t,x(:,1),'-',t,x_exact(:,1),'--')
title('ODE45 solution vs. Exact Solution');
ylabel('x-position(m)');
xlabel('time(s)');
legend('ODE45','Exact')
The error is in the following line:
plot(t,x(:,1),'-',t,x_exact(:,1),'--')
and it states that conversion from double to sym is not possible. Can anybody help? what am I doing wrong?

Respuesta aceptada

Star Strider
Star Strider el 5 de Oct. de 2014
Defining ‘t’ and other variables as double and then defining them later as symbolic caused those problems. I corrected them so that this has the virtue of working.
You can experiment with it to explore the different properties of the ode45 and Symbolic Math Toolbox solutions:
spring = @(t,x) [x(2); 1-(4*pi).^2.*x(1)];
time_period = [0 4];
[td,xd]=ode45(spring,time_period, [0; 0]);
%Call function spring:
% | function dxdt=spring(t,x) |
% | dxdt=[x(2), 1-(4*pi)^2*x(1)]; |
%2)
plot(td,xd(:,1));
title('Spring-Mass Function ODE45 Solution')
ylabel('x-position(m)');
xlabel('time(s)');
%3)
syms xs(t)
x_exact=dsolve('D2xs == 1-(16*pi^2)*xs', 'Dxs(0)=0', 't')
af_x_exact = matlabFunction(x_exact)
plot(td,xd(:,1),'-',td,af_x_exact(0.007,td),'--')
title('ODE45 solution vs. Exact Solution');
ylabel('x-position(m)');
xlabel('time(s)');
legend('ODE45','Exact')
I created ‘spring’ as an anonymous function because it was more convenient for me.
  2 comentarios
Erik
Erik el 6 de Oct. de 2014
Thank you for the prompt response. Your help was perfect. All I had to do was apply a 0.25 sec correction to the exact plot and I'm good to go. You are truly a lifesaver and may the karma gods rain good karma down upon thee.
Star Strider
Star Strider el 6 de Oct. de 2014
My pleasure!
I appreciate your good karma sentiments.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Symbolic Math Toolbox en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by