How to define the function to use for the composite trapezoidal rule?
Show older comments
Im trying to define the function to be integrated possibly in a sub-function, but I cant seem to do it without it saying INVALID.
My work is below.
Thanks
clc
clear
%intial conditions
t=linspace(1,10,10);
v=zeros(size(t));
m=1609.344/3600;%conversion from mph to m/s
for i=1:numel(t)
v(i)=((0.0011*(t(i)^6))-(0.02928*(t(i)^05))+(0.2807*(t(i)^4))-(1.1837*(t(i)^3))-(0.8283*(t(i)^2))+(41.234*(t(i))-3.3549))*m;
hold on
end
plot(t,v,'r*-')
title('9 Seconds of Car Driving-Speed(m/s)vs.Time(s)')
xlabel('Time(s)')
ylabel('Speed(m/S)')
a=1; %lower limit
b=10; %upper limit
n=9; %number of sub-intervals
r_error=0.1;%intial realtive error
i=0; %loop counter
I=0; %integral set to zero
%while loop to find new integral with a realtive error less than 0.0002%
while r_error>0.00002
h=(b-a)/n; %distnace of each separation
new_i=0; %intially set to zero
i=i+1; %increase counter by 1 every loop
for m=1:n
x_left=a+(i-1)*h;
x_right=a+(i*h);
f_left=f(x_left);
f_right=f(x_right);
new_i=(h/2)*(f_left+f_right)+I; %new integral
New_x=new_i; %new distance is equal to new integral
midpoint=(a+b)/2;
end
r_error=((new_i-I)/new_i)*100; %realtive error
n1(i)=n;
New_x=new_i;
n=n*2; %number of separtions doubled every loop
I=new_i; %new integral is stores as old integral for new loop
fprintf('Integral=%6.3f\n',I) %new integral value displayed to 3 decimal places
fprintf('Number of separations=%6.0f\n',n) % displaying number of separations
fprintf('Relative Error=%6.5f\n',r_error) %displaying relative error to 5 decimal places
end
function v=f(t)
v=((0.0011*t^6)-(0.02928*t^5)+(0.2807*t^4)-(1.1837*t^3)-(0.8283*t^2)+(41.243*t)-3.3549);
end
Accepted Answer
More Answers (1)
james carsley
on 24 Jul 2019
0 votes
Categories
Find more on Earth and Planetary Science 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!