# Numeric integration with Trapezoidal and Simpson's rule

조회 수: 25(최근 30일)
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 2020년 11월 25일
Is f a function ? or vector ? it seems you are trying to pass function as argument to a function

댓글을 달려면 로그인하십시오.

### 답변(1개)

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표시숨기기 이전 댓글 수: 2
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)

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!