How do I calculate acceleration with velocity and the code given?

153 views (last 30 days)
So this is how I got the velocity done and graphed but I can't figure out how to get the acceleration done. I get an error that the matrix dimensions aren't the same. I'm stuck as to where to go from here and can't find information regarding the code I need to use.
v=zeros(1,length(t)); % Create the velocity array - initially filled with zeros
v(1)=(x(2)-x(1))/(t(2)-t(1)); % first velocity point - method 1
v(2:end-1)=(x(3:end)-x(1:end-2))./(t(3:end)-t(1:end-2)); % method 3
v(end)=(x(end)-x(end-1))./(t(end)-t(end-1)); % last point - method 2
Calculation of acceleration versus time using numerical derivatives
a=zeros(1,length(t)); % Create the acceleration array
a(1)=diff(v(1))./diff(t);
a(2:end-1)=a1(end);
a(end)=gradient(v,0.01);

Answers (1)

Vladimir Sovkov
Vladimir Sovkov on 25 Jan 2020
Edited: Vladimir Sovkov on 25 Jan 2020
% sample data
t=0:0.1:10; % time
x=3+2*t+t.^2; % coordinate
[t,ind]=sort(t); % in a case time is not in an ascending order
x=x(ind);
k=find(t(1:end-1)==t(2:end)); % in a case there are coinciding times, exclude them
if ~isempty(k)
t(k)=[];
x(k)=[];
end
figure;
plot(t,x,'.-');
title('Coordinate');
xlabel('t');
ylabel('x');
% velocity
v=diff(x)./diff(t); % velocities at times tv; a vector of the length less than t, x by 1
tv = (t(1:end-1)+t(2:end))/2; % times related to v; a vector of the length less than t, x by 1
figure;
plot(tv,v,'.-');
title('Velocity');
xlabel('tv');
ylabel('v');
% acceleration
a=diff(v)./diff(tv); % accelerations at times ta; a vector of the length less than t, x by 2
ta = (tv(1:end-1)+tv(2:end))/2; % times related to a; a vector of the length less than t, x by 2
figure;
plot(ta,a,'.-');
title('Acceleration');
xlabel('ta');
ylabel('a');

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!