Deferential Equation Animation - Spring Mass Undamped

 

 

Click on Next and Prev button so that some intuitive images forms in your head.

 

 

 

 

 

< Code 1 >

 

clear all;

 

tn = 100;

tstep = 20/100;

t = 0:tstep:tstep*tn;

%t = 0:0.02*pi:10*pi;

 

 

tmax = 20;

global k = 3.0;

global m = 1.0;

  

function dy_dt = f(y, t)

  global k;

  global m;

  dy_dt = zeros (2,1);

  dy_dt(1) = y(2);

  dy_dt(2) = -k/m .* y(1);

endfunction

 

y2_init = 0.0;

y1_init = 1.0;

 

y0 = [y1_init y2_init];

y = lsode ("f", y0, t);

 

d = y(:,1);

 

hFig = figure(1,'Position',[300 300 780 500]);  

 

subplot(3,1,1);

tx = 0.2;

text(tx,1.0,"m x''(t) + k x(t) = 0",'FontSize',16,'fontweight','bold');

 

tx = 0.3;

tStr = sprintf("m = %0.2f, k = %0.2f",m,k);

text(tx,0.7,tStr,'FontSize',14);

 

tStr = sprintf("%0.2f x''(t) + %0.2f x(t) = 0", ...

                m,k);

text(tx,0.4,tStr,'FontSize',14);

 

tStr = sprintf("@ t = %0.2f", t(end));

text(tx,0.1,tStr,'FontSize',14);

 

axis([0 7 0 1]);

set(gca,'Visible','off')

 

subplot(3,1,2);

xResting = 2;

x1 = 0;

y1 = 0.1;

x2 = xResting + d(end);

y2 = 0.1;

mw = 0.2; % width of the maxx

mh = 0.2; % height of the maxx

 

hold on;

line([xResting xResting],[0 0.6],'Color','blue');

line([x2 x2],[0 0.5],'Color','blue');

line([xResting x2],[0.4 0.4],'Color','red','LineWidth',4);

text(xResting - 0.15 ,0.7,'x = 0','FontSize',16,'fontweight','bold');

DrawSpring(x1,y1,x2,y2,12,0.1,0.1,0.1);

DrawBox(x2,y2,mw,mh,0);

axis([0 5 0 1]);

set(gca,'xticklabel',[]);set(gca,'yticklabel',[]);

set(gca,'xtick',[]);set(gca,'ytick',[]);

 

 

subplot(3,1,3);

hold on;

plot(t,y(:,1),'r-','LineWidth',2);

plot(t(end),d(end),'ro','MarkerFaceColor',[1 0 0],'MarkerSize',8);

line([t(end) t(end)],[0 d(end)],'Color','black');

xlabel('time');

xlim([0 tmax]);

ylim([-2 2]);

%xtick = 0:pi:10*pi;

%set(gca,'xtick',xtick);

%set(gca,'xticklabel',{'0','pi','2pi','3pi','4pi','5pi','6pi','7pi','8pi','9pi','10pi'});

grid on;

hold off;