Conversion to double from sym is not possible
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Erik
am 5 Okt. 2014
Kommentiert: Star Strider
am 6 Okt. 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?
0 Kommentare
Akzeptierte Antwort
Star Strider
am 5 Okt. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Symbolic Math Toolbox 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!