Conversion to double from sym is not possible

조회 수: 5 (최근 30일)
Erik
Erik 2014년 10월 5일
댓글: Star Strider 2014년 10월 6일
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?

채택된 답변

Star Strider
Star Strider 2014년 10월 5일
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
Erik
Erik 2014년 10월 6일
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 2014년 10월 6일
My pleasure!
I appreciate your good karma sentiments.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by