Riemann Sums; how to input interval as well as function f(x)?
Show older comments
%I have not visited this function in a while and can not see why it is not working. no matter what I use for 'n', it says it is undefined? should there be a seperate f(x) function used? These are all the requirements, I'm not asking for anyone to do it for me since I have most of it done, but the ones with asterisks are the ones im confused with.
1. Input endpoints of interval of integration [a,b].
*2. Input the Integrand function f(x)
*3. Offer the user a menu of options for the sample point chosen in each subinterval (left, right endpoints, midpoint and random point within subinterval)
4. Plot function on [a,b]
5. For regular partition of [a,b], plot approx. rectangles under graph f(x)
6. Compute Sum under rectangles
7. Display Riemann sum on the figure
8. Output a well-formatted table of rectangle areas for n = 2, 4, 8, 16, 32, 64, 128, 256.
9. Record frames for the cases n = 2, 4, 8, 16, 32, 64, 128, 256, and display movie showing convergence of rectangles.
function riemann_krr(a,b,n)
zz = linspace(a,b);
yy = f(zz); yy1 = g(zz);
w = 0*zz;
plot(zz,yy,zz,yy1,zz,w,'k');
for j = 1:20
n=2*j;
x=linspace(a,b,n+1);
xr = x+rand(1,n+1)*(b-a)/n;
hold on
for i = 1:n
ys = f(xr(i)); yl = g(xr(i));
xp = [x(i) x(i) x(i+1) x(i+1)];
yp = [yl ys ys yl];
fill(xp,yp,'b')
plot(xp, yp)
whitebg([.478, .617, .9])
set(gcf,'Color',[.549 .09 .09]);figure(1)
end
plot(zz,yy,zz,w,'k')
M(j) = getframe;
pause(.5)
clf
hold off
end
movie(M)
Answers (1)
Geoff Hayes
on 3 May 2015
Keith - you have only mentioned part of the error message, that something is undefined. Presumably it is f and g since your third line of code is
yy = f(zz); yy1 = g(zz);
and f and g are not defined prior to their use here. If you want f to be any function (so long as it accepts a scalar input and returns a scalar output) then it must be defined as an input variable in your function signature like
function riemann_krr(f,a,b,n)
f is a handle to a function. See function handles for details on how to create a function handle. (Something similar will have to be done for g as well.)
As for the third point (from above) it seems that you are required to build a GUI that will allow the user to choose which (left, right, middle) Riemann sum he or she wishes to compute.
Categories
Find more on Mathematics 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!