MATLAB: Matlab Code for the Gauss Legendre Quadrature

gauss legendre

I need help contsructing the code for the gauss legendre quadrature using n =2 , 4, and 6. i was able to get the value for n =2 but after that im kind of lost.
%% parameters
a = -1; % lower bound
b = 1; % upper bound
n = [-1/sqrt(3) 1/sqrt(3)]; %location values for n=2
n1 = [-0.86113 -0.33998 0.33998 0.86113]; %location values for n=4
n2 = [-0.93246 -0.66120 -0.23861 0.23861 0.66120 0.993246]; % location values for n=6
w = 1; %weight for n=2
w1 = [0.34785 0.625214]; %weights for n=4
w2 = [0.17132 0.36076 0.6791]; % weights for n=6
f = @(x) (1)/(x.^2 * (sqrt(x.^2 +1)));%function
%% Gauss_Legendre Quadrature
% n=2
for i = 1:length(n)
h = n(i);
y(i) = w*f(h);
end
gaussleg1 = sum(y); % sum of wi*fi for n=2
%n=4
%n=6

Best Answer

Have your vectors of weights be the same size as your vectors of locations, ordered so that corresponding weights and locations are in the same position:
%% parameters
a = -1; % lower bound
b = 1; % upper bound
n = [-1/sqrt(3) 1/sqrt(3)]; %location values for n=2
n1 = [-0.86113 -0.33998 0.33998 0.86113]; %location values for n=4
n2 = [-0.93246 -0.66120 -0.23861 0.23861 0.66120 0.993246]; % location values for n=6
w = [1 1]; %weight for n=2
w1 = [0.34785 0.625214 0.625214 0.34785]; %weights for n=4
w2 = [0.17132 0.36076 0.6791 0.6791 0.36076 0.17132]; % weights for n=6
f = @(x) (1)./(x.^2 .* (sqrt(x.^2 +1)));%function
%% Gauss_Legendre Quadrature
% n=2
gaussleg = sum(w.*f(n));
%n=4
gaussleg1 = sum(w1.*f(n1));
%n=6
gaussleg2 = sum(w2.*f(n2));
Higher precision in your weights and locations will give more accurate results.
(edit) I also changed f slightly so that you could pass in the entire vector of locations at once.
Related Question