MATLAB Answers

Numeric integration with Trapezoidal and Simpson's rule

์กฐํšŒ ์ˆ˜: 25(์ตœ๊ทผ 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
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)

๋Œ“๊ธ€์„ ๋‹ฌ๋ ค๋ฉด ๋กœ๊ทธ์ธํ•˜์‹ญ์‹œ์˜ค.

ํƒœ๊ทธ

Community Treasure Hunt

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

Start Hunting!

Translated by