How to make a UDF that calculates the Midpoint Rule
    5 views (last 30 days)
  
       Show older comments
    
function output = Midpoint(f,a,b,h)
%%%%%%%% Inputs
% f  - This is a function handle defining the right-hand side of the ODE we
%      are solving, it should be a function of two arguments
% a - This is the initial x value
% b  - This is the final x value where you want to approximate the solution
%      to the ODE
% h  - This is the step-size to use in determining the t-grid
%%%%%%%% Outputs
% t  - This will be a vector of the t-grid values 
% y  - This will be a vector of the approximate solution evaluated at
%           each of the t-grid values
deltax=(b-a)/h; %subintervals 
x=[a:deltax:b]; %need to create a vector of n+1 evenly spaced points
mpr=0; %initialize midpoint rule
for k=1:h;
   mpr=mpr+f((2*k+1)/2)*deltax;
   output=mpr
end
end
this is what i HAVE SO FAR
0 Comments
Answers (1)
  Alan Stevens
      
      
 on 4 Oct 2020
        Don't confuse x with t!   The following might help.  I'll leave you to turn it into a function:
f = @(x,y) x+y; % function of two arguments  f = dy/dx  (y = 2exp(x)-x-1)
a = 0;          % lower limit
b = 1;          % upper limit
n = 100;        % number of intervals
deltax=(b-a)/n; % stepsize
x = a:deltax:b; % vector of evenly spaced points 
y = zeros(size(x)); % storage space for y.
y(1) = 1;       % initial value for y
for i = 1:n
    mpx = x(i) + deltax/2;       % midoint between x(i) and x(i+1)
    mpy = y(i) + y(i)*deltax/2;  % value of y at midpoint
   y(i+1)= y(i)+f(mpx,mpy)*deltax;  % explicit midpoint rule 
end
plot(x,y),grid
0 Comments
See Also
Categories
				Find more on Numerical Integration and Differential Equations 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!
