Numeric integration with Trapezoidal and Simpson's rule

7 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by