필터 지우기
필터 지우기

How to make a UDF that calculates the Midpoint Rule

조회 수: 3 (최근 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 CenterFile Exchange에서 Contour Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by