Question: This question involves using a Matlab code (trapezoidal rule) from the textbook, Elementary Numerical Analysis. I need to code to work for the given problem
This question involves using a Matlab code (trapezoidal rule) from the textbook, Elementary Numerical Analysis. I need to code to work for the given problem below.
Here is the code straight from the textbook. Now I don't need those f_values, since my f(x) is (e^x)*cos(4x). Please help me figure this out, because Matlab is yelling at me and I don't understand why.
function [integral,difference,ratio]=trapezoidal(a,b,n0,index_f)
%Using the program for the trapezoidal rule given in the text, prepare a
%table of values of T_n(f) for n=2,4,8,...,512 for the following integrals.
%Also find the errors and the rations by which the errors decrease.
%
%n=n0,2*n0,4*n0,...,256n0,512*n0
%The value of n0 must be a positive integer.
%The corresponding numerical integrals are returned in the vector inegral.
%The difference of successive numerical integrals are returned in the
%vector difference:
% difference(i)=integral(i)-integral(i-1), i=2,...,10
%The entries of the ration given the rate od decrease in these differences.
%The parameter index_f allows the user to do calculations with multiple
%integrands.
%Initialize output vectors.
integral=zeros(10,1);
difference=zeros(10,1);
ratio=zeros(10,1);
%Intitialize for trapeziodal rule
sumend=(f(a,index_f)+f(b,index_f))/2;
sum=0;
%Intitialize for case of n0>2.
if(n0>2)
h=(b-a)0;
for i=2:2:n0-2
sum=sum+f(a+i*h,index_f);
end
end
%Calculate the numerical integrals, doing each by appropriately modifying
%the preceding case.
for i=1:10
n=n0*2^(i-1);
h=(b-a);
for k=1:2:n-1
sum=sum+f(a+k*h,index_f);
end
integral(i)=h*(sumend+sum);
end
%Calculate the differences of the successive trapezoidal rule integrals and
%the ratio of decrease in these differences.
difference(2:10)=integral(2:10)-integral(1:9);
ratio(3:10)=difference(2:9)./difference(3:10);
function f_value=f(x,index)
%This defines the integrand
switch index
case 1
f_value=exp(-x.^2);
case 2
f_value=1./(1+x.^2);
case 3
f_value=1./(2+cos(x));
end
2. Using the program for the trapezoidal rule given in the of prepare a text, table values of Tn(f) for n 2, 4, 8 512 for the following integrals. Also find the errors and the ratios by which the errors decrease n 2, 2. 2-512 e" 1 (a) e cos (4x) dx 17 2. Using the program for the trapezoidal rule given in the of prepare a text, table values of Tn(f) for n 2, 4, 8 512 for the following integrals. Also find the errors and the ratios by which the errors decrease n 2, 2. 2-512 e" 1 (a) e cos (4x) dx 17
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
