forked from yanastaneva8/least-squares-fitting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodifiedGramSchmidt.m
43 lines (31 loc) · 914 Bytes
/
modifiedGramSchmidt.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
% 2019862s
% Assessed Coursework 1: Least Squares Fitting
function [Q,R]=modifiedGramSchmidt(A)
% Store dimensions of matrix A
[m,n]=size(A);
% Inititate zero matrices for the reduced Q and R
Q=zeros(m,n);
R=zeros(m,n);
% Initiate a zero column vector
v=zeros(m,1);
% For loop for extracting columns from the matrix A
for i=1:n;
v(:,i)=A(:,i);
end
% For loop which implements the modified Gram-Schmidt
for i=1:n;
% Diagonal entry of R is the 2-norm of the i-th column vector
R(i,i)=norm(v(:,i),2);
% Compute the i-th column of Q
Q(:,i)=v(:,i)/R(i,i);
for j=i+1:n;
% Compute the off-diagonal entries of R
R(i,j)=Q(:,i)'*v(:,j);
% Update the next column vector to be used
% in the next iteration
v(:,j)=v(:,j)-R(i,j)*Q(:,i);
end
end
% Make sure to extract the reduced QR
R=R(1:n,:);
Q=Q(:,1:n);