How to make a UDF that calculates the Midpoint Rule

1 回表示 (過去 30 日間)
Aren Arslanyan
Aren Arslanyan 2020 年 10 月 3 日
回答済み: Alan Stevens 2020 年 10 月 4 日
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

回答 (1 件)

Alan Stevens
Alan Stevens 2020 年 10 月 4 日
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

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by