hw4: ex1 and ex3 done

This commit is contained in:
Claudio Maggioni 2020-05-14 22:23:08 +02:00
parent 7f310bd0de
commit b881fdd21c

View file

@ -1,4 +1,4 @@
%% Assignment 2 %% Assignment 4
% Name: Claudio Maggioni % Name: Claudio Maggioni
% %
% Date: 19/3/2019 % Date: 19/3/2019
@ -15,74 +15,76 @@
% %
%% Problem 3 %% Problem 3
format long clear;
A = [4 3 2 1; 8 8 5 2; 16 12 10 5; 32 24 20 11];
[L,U,P] = pivotedOuterProductLU(A);
display(L);
display(U);
display(P);
%% Problem 6 n=10;
[X,Y] = meshgrid((0:2000)/2000); f = @(x) (exp(-(x^2)/2)/sqrt(2*pi));
A = exp(-sqrt((X-Y).^2)); x_5 = computeEquidistantXs(5);
L = outerProductCholesky(A); x_10 = computeEquidistantXs(10);
disp(norm(L*L'-A, 'fro')); x_5c = computeChebyshevXs(5);
x_10c = computeChebyshevXs(10);
%% Problem 3 (continued) xe = (-1:0.01:1)';
y = zeros(size(xe));
function [L,U,P] = pivotedOuterProductLU(A) for i = 1:size(xe, 1)
dimensions = size(A); y(i) = f(xe(i));
n = dimensions(1);
p = 1:n;
L = zeros(n);
U = zeros(n);
for i = 1:n
values = A(:,i);
values(values == 0) = -Inf;
[~, p_k] = max(values);
k = find(p == p_k);
if k == -Inf
disp("Matrix is singular");
L = [];
U = [];
P = [];
return
end
p(k) = p(i);
p(i) = p_k;
L(:,i) = A(:,i) / A(p(i),i);
U(i,:) = A(p(i),:);
A = A - L(:,i) * U(i,:);
end
I = eye(n);
P = zeros(n);
for i = 1:n
P(:,i) = I(:,p(i));
end
P = transpose(P);
L = P * L;
end end
%% Problem 6 (continued) p_5 = computePolypoints(f, xe, x_5, 5);
p_10 = computePolypoints(f, xe, x_10, 10);
function [L] = outerProductCholesky(A) p_5c = computePolypoints(f, xe, x_5c, 5);
if ~all(eig(A) >= 0) p_10c = computePolypoints(f, xe, x_10c, 10);
disp("matrix is not positive definite");
L = []; figure;
return; subplot(1,2,1);
end plot(xe, p_5, xe, p_10, xe, y);
dimensions = size(A); subplot(1,2,2);
n = dimensions(1); plot(xe, p_5c, xe, p_10c, xe, y);
L = zeros(n);
function x = computeEquidistantXs(n)
for i = 1:n x = zeros(2*n+1,1);
L(:, i) = A(:, i) / sqrt(A(i,i)); for i = 1:2*n+1
A = A - L(:, i) * transpose(L(:, i)); x(i) = (i-n-1)/n;
end
end
function x = computeChebyshevXs(n)
x = zeros(2*n+1,1);
for i = 1:2*n+1
x(i) = cos((2*i - 1) *pi / (4*n + 2));
end
end
function p = computePolypoints(f, xe, x, n)
p = zeros(size(xe));
for i = 1:(2*n+1)
e_i = zeros(2*n+1, 1);
e_i(i) = 1;
N = NewtonInterpolation(x, e_i);
p = p + f(x(i)) * HornerNewton(N, x, xe);
end
end
% Assuming x and y are column vectors with the same length
function N = NewtonInterpolation (x,y)
n = size(x, 1);
N = y;
for i = 1:n
N(n:-1:i+1) = (N(n:-1:i+1) - N(n-1:-1:i)) ./ (x(n:-1:i+1) - x(n-i:-1:1));
end
end
% N is the array of coefficients
%
% xi evaluation points
function p = HornerNewton(N, x, xe)
n = size(x, 1);
p = ones(size(xe, 1), 1) * N(n);
for i = n-1:-1:1
p = p .* (xe - x(i)) + N(i);
end end
end end