Numeric integration with Trapezoidal and Simpson's rule
22 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
VBBV
el 25 de Nov. de 2020
Is f a function ? or vector ? it seems you are trying to pass function as argument to a function
Respuestas (1)
Jon
el 25 de Nov. de 2020
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 comentarios
Jon
el 25 de Nov. de 2020
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)
Ver también
Categorías
Más información sobre Downloads en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!