- I recommend using a function rather than manually asking for input during run time.
- In the loop use step number rather than the x-position as the running index. This way you can access the ii th component of x to evaluate the function.
How to use a loop to create a function calculate a numerical estimate of the integral?
4 views (last 30 days)
Show older comments
I'm supposed to be using the left rectangle rule
to write code for a function that could calculate the numerical estimate of the integral entered with the function entered but mine just get's back zeroes no matter what I do. What am I doing wrong? I'm supposed to using a function handle but i'm confused as to how in this context. Can anybody help me? I know my code is a total mess
% code%
I = w4q1i(f,[a,b,n]) calculates a numerical estimate of the integral of
% function f on the given range, using the left-rectangle rule %
% INPUTS
% f : function handle
% range = [a,b,n] : range of integration (a,b) with n subintervals
a = input('Enter the upper limit of the range : ');
b = input('Enter the Lower Limit of the range : ');
n = input('Enter number of required sub intervals : ');
x = linspace(b,a,n+1);
f = input('Enter Function with respect to x : ');
m=x(2)-x(1);
pp=zeros(1,x(n+1))
for q=a:b;
pp(q+m)=f(x);
end
k=sum(pp);
I=m*k
end
What am I doing wrong?
0 Comments
Answers (1)
Mischa Kim
on 14 Feb 2014
Edited: Mischa Kim
on 14 Feb 2014
Georgia, check out the following:
function sol = my_int(f, ablim, n)
% function f on the given range, using the left-rectangle rule %
% INPUTS
% f : function handle
% range = [a,b,n] : range of integration (a,b) with n subintervals
x = linspace(ablim(1),ablim(2),n+1);
m = (ablim(2)-ablim(1))/n;
sol = 0;
for ii = 1:length(x)
sol = sol + m*f(x(ii));
end
end
which you would call from the MATLAB command window using:
f = @(x) x.^2;
sol = my_int(f, [0 2], 10);
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!