Conversion to double from sym is not possible
1 view (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Star Strider
on 5 Oct 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 Comments
More Answers (0)
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!