Numeric integration with Trapezoidal and Simpson's rule

3 ビュー (過去 30 日間)
Jhonie Habimana
Jhonie Habimana 2020 年 11 月 25 日
コメント済み: Jon 2020 年 11 月 25 日
I am trying to write a code that allows a user pick between Trapezodal and simpsons method of integration and then after picking the code will let the integrate a given formula 𝑦 = 𝑥 −1 + √𝑥𝑒 ^x . My code is not running however and i was wondering where I may be going wrong
clc
clear
%Lower limit (a)
a = input('What is your lower limit (a)? \n');
% Upper limit (b)
b = input('What is your upper bound (b)? \n');
% Subintervals, it is an even number
N = input('How many subintervals (N)? \n');
%y=1./x+ sqrt(x).*exp(x);
% Calculating the integral
clear
clc
function s=simprl(f,a,b,N)
h=(b-a)/N;
s1=0;
s2=0;
for i=1:N
x=a+h*(2*i-1);
s1=s1+f(x);
end
for i=1:(N-1)
x=a+h*2*i;
s2=s2+f(x);
end
s=h*(f(a)+f(b)+4*s1+2*s2)/3; %composite simpsons formula without error
fprintf('s =%f\n',simprl)
end
  1 件のコメント
VBBV
VBBV 2020 年 11 月 25 日
Is f a function ? or vector ? it seems you are trying to pass function as argument to a function

サインインしてコメントする。

回答 (1 件)

Jon
Jon 2020 年 11 月 25 日
You may have other problems too, but it looks like you clear all of your variables right after you just defined your limits and number of subintervals. You should not have the lines of code
% Calculating the integral
clear
clc
  3 件のコメント
Jhonie Habimana
Jhonie Habimana 2020 年 11 月 25 日
Thank you so much I will implement this immediately, how do I call a function
Jon
Jon 2020 年 11 月 25 日
In general if you have a function, lets call it myfun with for example arguments a,b,c that returns one argument then somewhere in your code you would just use for example
% just an illustrative example
a = 2
b =26.3
c = 15
y = myfun(a,b,c)
In your case it is a little more complicated because the first argument to your function is a function. (the integrand) You need to pass a handle to that function. See https://www.mathworks.com/help/matlab/matlab_prog/pass-a-function-to-another-function.htmlHere's one way to do it
% assuming a,b, and N are defined earlier in your code, then use
f = @(x) 1./x+ sqrt(x).*exp(x);
y = simprl(f,a,b,N)

サインインしてコメントする。

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by