Visualization of motion, force, or other vector in MATLAB

Motion and force visualization by MATLAB. It would be useful for debug, presentation, etc. The sample codes are given here:

 theta=0:0.05:2pi; 
x=cos(theta);
y=sin(theta); 
t=0:0.1:10; 
No=length(t); 
posx=sin(t); % position of circle 
vel=sin(t+pi/2); % velocity 
acc=sin(t+pi); % acceleration 
F=-(5acc+20vel.abs(vel)); % force
Fmax=max(abs(F));

fh3 = figure(2);
ah1 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.84 0.85 0.15]);
ah2 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.60 0.85 0.15]);
ah3 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.1 0.85 0.425]);

for i=1:No
     xn=x+posx(i);
     plot(t,vel,'b',t(i),vel(i),'o','Parent',ah1);
     xlabel(ah1,'time [s]');
     ylabel(ah1,'vel [m/s]'); 
     legend(ah1,'v');
     plot(t,acc,'b',t(i),acc(i),'o','Parent',ah2);
     xlabel(ah2,'time [s]');
     ylabel(ah2,'acc [m/s^2]'); 
     legend(ah2,'a');
     plot(xn,y,'Parent',ah3);
     axis([-5 5 -2.2 2.2]);
     hold on;
     quiver3(posx(i),0,0,F(i),0,0,2/Fmax,'r');
     xlabel(ah3,'x [m]'); 
     ylabel(ah3,'y [m]');
     legend(ah3,'body','F=-5a-20v|v|');
     pause(.1) ;
     hold off
end

if you want to create a video to save the animation, the following codes would be helpful.

 theta=0:0.05:2*pi;
x=cos(theta);
y=sin(theta);
t=0:0.1:10;
No=length(t);
posx=sin(t); % position of circle
vel=sin(t+pi/2); % velocity
acc=sin(t+pi);  % acceleration
F=-(5*acc+20*vel.*abs(vel)); % force
Fmax=max(abs(F));

fh3 = figure(2);
ah1 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.84 0.85 0.15]);
ah2 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.60 0.85 0.15]);
ah3 = axes('Parent',fh3,'Units','normalized','Position',[0.1 0.1 0.85 0.425]);

myVideo = VideoWriter('forceVisualization');
myVideo.FrameRate = 10;
open(myVideo);
for i=1:No
    xn=x+posx(i);
    plot(t,vel,'b',t(i),vel(i),'o','Parent',ah1);
    xlabel(ah1,'time [s]');
    ylabel(ah1,'vel [m/s]'); 
    legend(ah1,'v');
    plot(t,acc,'b',t(i),acc(i),'o','Parent',ah2);
    xlabel(ah2,'time [s]');
    ylabel(ah2,'acc [m/s^2]'); 
    legend(ah2,'a');
    plot(xn,y,'Parent',ah3);
    axis([-5 5 -2.2 2.2]);
    hold on;
    quiver3(posx(i),0,0,F(i),0,0,2/Fmax,'r');
    xlabel(ah3,'x [m]'); 
    ylabel(ah3,'y [m]');
    legend(ah3,'body','F=-5a-20v|v|');
    pause(.1) ;
    frame=getframe(gcf);
    writeVideo(myVideo,frame);
    hold off
end
close(myVideo);

Leave a Comment

Your email address will not be published. Required fields are marked *