Numerical Integration and Approximation

7 views (last 30 days)
Abraham
Abraham on 17 Oct 2018
Commented: Torsten on 17 Oct 2018
Hi, So I have this function that takes data sample locations and function samples at those locations as input and returns an approximation of the integral over the sample range based on the trapezoidal rule. I named it trapint.m. But now I need to test this function with an integral to see if it converges to a solution, using a range of 1-10 and a step size of 3. But it has not been successful. This is the integral that I want to test - [integralx^2*e^x dx]. I have attached my code for reference. Please, what is missing or what do I need to add. Thanks in advance
This is my code:
function I = trapint(x,fx)
I = NaN; % Default value
% Validation
% Check number of inputs
if(nargin ~= 2)
disp('Number of inputs is not equal to two. Please provide two arguments');
return
end
%Check if the inputs are of same length
if(length(x)~=length(fx))
disp('The provided vectors are not of same length');
return
end
%Check if the inputs are vectors
if(~isvector(x) && ~isvector(fx))
disp('Both the provided inputs are not vectors. Please provide vector inputs');
return
elseif(~isvector(x))
disp('The provided x value is not vector. Please provide vector values for x');
return
elseif(~isvector(fx))
disp('The provided fx value is not vector. Please provide vector values for fx');
return
end
%Check if the inputs are numeric
if(~isnumeric(x) && ~isnumeric(fx))
disp('Both the provided inputs are not numeric. Please provide numeric inputs');
return
elseif(~isnumeric(x))
disp('The provided x value is not numeric. Please provide numeric values for x');
return
elseif(~isnumeric(fx))
disp('The provided fx value is not numeric. Please provide numeric values for fx');
return
end
mean_fx = mean([fx(1:end-1);fx(2:end)]);
dx = diff(x);
I = sum(mean_fx.*dx);

Answers (1)

Torsten
Torsten on 17 Oct 2018
x = linspace(1,10,3);
fx = x.^2.*exp(x);
I = trapint(x,fx)
  4 Comments
Abraham
Abraham on 17 Oct 2018
This is what I'm trying to do: I need to test the integral by using the function to approximate the integral, to see if it converges to a solution. In other words, Approximation of integral of fx over a sampled range.
Torsten
Torsten on 17 Oct 2018
What do you mean by "approximate the integral as the number of step increases" ? In your original post, you fixed the range to x=1 to x=10 and the stepsize to 3. And that's what the code does.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!