Borrar filtros
Borrar filtros

How to make a UDF that calculates the Midpoint Rule

3 visualizaciones (últimos 30 días)
Aren Arslanyan
Aren Arslanyan el 3 de Oct. de 2020
Respondida: Alan Stevens el 4 de Oct. de 2020
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

Respuestas (1)

Alan Stevens
Alan Stevens el 4 de Oct. de 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

Categorías

Más información sobre Contour Plots en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by