The mid-point rule as a function in matlab

24.1k Views Asked by At

How would I go about creating a function in matlab which would calculate the following

$$M_c(f)=h \sum_{i=1}^N f(c_i)$$

where

$h=\frac{b-a}{N}, \\c_i=a+0.5(2i-1)h,\\ i=1,\ldots,N$

What I have tried so far is

function(M(f))= composite_midpoint(f)

h=(b-a)/N
for i=1:1:N
   c_i=a+0.5*(2i-1)*h
   M(f) = h*(sum + f)
end

Sorry about not inserting the matlab code directly, I'm not sure how to do it.

2

There are 2 best solutions below

5
On BEST ANSWER

First run this outside the function:

a = 6; 
b = 4.234;
N = 10;

Then save this function to a file called compositemidpoint.m (in your current directory)

function M = compositemidpoint(a,b,N)
h = (b-a)/N
i = 1:N
c_i = a+0.5*(2*i-1)*h
f = log(c_i) + c_i.^2 % A sample function
M = h*sum(f);

Then call it by typing:

compositemidpoint(a,b,N)
2
On

Here's my solution, which is vectorized (for loops are bad in matlab).

function Mf=midpoint_rule(a,b,N,f)

h=(b-a)/N;
%ci are your evaluation points
ci=linspace(a+h/2,b-h/2,N-1);
%This evaluates the function f, which is another matlab function
y=f(ci);
%you can just add up the vector y and multiply by h
Mf=h*sum(y);

end

For example, you can save another .m file Myfunction.m, that might look like:

function y=Myfunction(x)

%The dot means "pointwise"
y=x.^2

end

Then, in the main window, you would evaluate the integral by saying "midpoint_rule(1,2,100,@Myfunction)". The "at" symbol tells matlab you'll be using a matlab function called "Myfunction".