MATLAB: Integration using function calls

gaussianintegrationMATLAB

How can I use the gauss quadrature function to estimate the area under a function. I also want to be able to input the number of segments used in the integration. This is what I've done so far, but I want a vector output for the gauss function that I can graph, but I keep getting just one scalar output. The first code is my main program that calls on the gauss function that is written at the bottom. My main program works well and I've tested it without the Gauss function, but something is wrong with the syntax of the Gauss function because I only get one scalar output. What's wrong?
Main Program
clear
Num = [2,4,8,10,14,18,20,30,40,50,60,80,100,1000,2500,5000];
a=-1.0;
b=12.3;
func = ('(.2*x.^3)-(2.5*x.^2)+(35.1*(sin(x).^2))+(5.23*x)-27');
for i = 1:length(Num)
N = Num(i)+1;
dx=(b-a)/(N-1);
x = a:dx:b;
f = inline(func);
[trap_area(i)]= hw5_Trap(f,a,b,N);
[simp_area(i)]= hw5_Simp(f,a,b,N);
[gauss_area] = hw5_Gauss(f,a,b,N);
end
semilogx(Num,trap_area,Num,simp_area,Num,gauss_area)
Gauss Quadrature Function
function [out] = hw5_Gauss(f,a,b,N)
dx=(b-a)/(N-1);
for i = 1:N-1
s = a + (i-2)*dx;
e = s + dx;
xs=((e+s)+((e-s)*(-1/sqrt(3))))/2;
xe=((e+s)+((e-s)*(1/sqrt(3))))/2;
gauss=(f(xs)+f(xe))*(dx/2);
end
out = gauss;

Best Answer

You forgot the index in the first part:
for i = 1:length(Num)
...
% [gauss_area] = hw5_Gauss(f,a,b,N);
% ==>
[gauss_area(i)] = hw5_Gauss(f,a,b,N);
end
There seems to be something wrong with your hw5_Gauss also: The output value depends on the last iteration of the FOR loop only.
Related Question