If statement in a function
Show older comments
I have a function that outputs the speeds at times from 0:25 seconds and there are different equations for different times. I would like to know however how to make the function stop at 25 seconds rather than keep going on. As a reference i was trying to use the composite trapezoidal rule to find the distance travelled over time by a camaro for 25 seconds.
format short
clear all
clc
Speed_first=@(t)0.1553567*(t.^6)-2.0416*(t.^5)+9.1837*(t.^4)-14.829*(t.^3)-1.3703*(t.^2)+32.821*t-1.3155;
Speed_second=@(t)0.003980879*(t.^5)-0.2247*(t.^4)+4.8682*(t.^3)-50.442*(t.^2)+254.67*t-430.66;
Speed_third=@(t)-0.073*(t.^2)+6.1802*t+40.423;
time=0:0.01:25;
speed=[];
l=length(time);
for i=1:l
if (time(i)<5)
speed(i)=Speed_first(time(i));
elseif (time(i)<15.4)
speed(i)=Speed_second(time(i));
else
speed(i)=Speed_third(time(i));
end
end
subplot(2,1,1)
plot(time,speed)
ylabel('Speed')
xlabel('Time')
title('Time against speed')
N=2;
Er = 100;
old_integral = 100;
Number_sections=[];
Integrals=[];
while Er > 0.00002
[integral,Distance_vec,time_vec]=inttrapezoidal(N);
Number_sections = [Number_sections N];
Integrals = [Integrals integral];
N = N*2;
Er=abs(((integral-old_integral)/integral)*100);
old_integral=integral;
fprintf('\n Integral= %g; number of Sections = %g; Relative Error = %f\n',integral,N, Er)
end
subplot(2,1,2)
plot(time_vec, Distance_vec);
title('Cumulative distance by time');
xlabel('Time');
ylabel('Distance travelled');
figure()
semilogx(Number_sections,Integrals);
title('Distance travelled by number of sections');
xlabel('Number of Sections');
ylabel('Distance travelled');
function [integral,Distance_vec,time_vec] = inttrapezoidal(N)
a = 0;
b = 25;
h = (b-a)/N;
Distance_vec(1) = 0.0;
for m = 2:N
x_left = a+(m-1)*h;
x_right = a+m*h;
f_left = f(x_left);
f_right = f(x_right);
Distance_vec(m) = Distance_vec(m-1)+h/2*(f_left+f_right);
time_vec(m)=x_left;
end
integral=Distance_vec(end);
end
function v = f(time)
if time<=5
Speed = 0.1553567*(time.^6)-2.0416*(time.^5)+9.1837*(time.^4)-14.829*(time.^3)-1.3703*(time.^2)+32.821*time-1.3155;
elseif time>=5 && time<15.4
Speed = 0.003980879*(time.^5)-0.2247*(time.^4)+4.8682*(time.^3)-50.442*(time.^2)+254.67*time-430.66;
else
Speed =-0.073*(time.^2)+6.1802*time+40.423;
end
v=Speed*0.47404;
end
but as you can see at the end i cant make my function stop at 25 seconds.
Accepted Answer
More Answers (0)
Categories
Find more on Graphics Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!