66.0k views
4 votes
Based on the following code given in class, write codes in MATLAB to find the QR decomposition of the matrix, show your codes and the Q and the R you obtained.

A= randi ([−8,8],7,5);
[m,n]=size(A);
​Q= zeros (m,n);
R= zeros (n,n);
P=0;
for j=1:
n Q(:,j)=A(:,j);
if j>=2 for k=1:
j−1 R(k,j)=Q(:,k)⋅∗A(:,j);
P=P+Q(:,k)∗R(k,j);
end P=0; Q(:,j)=Q(:,j)−P; R(j,j)=norm(Q(:,j));
Q(:,j)=Q(:,j)/R(j,j); P=0;

User ConanG
by
8.7k points

1 Answer

3 votes

Final answer:

The QR decomposition of a matrix can be computed in MATLAB using either built-in functions or by implementing the Gram-Schmidt process.

The provided code had several issues, and the corrected MATLAB code above now properly computes the decomposition, producing an orthogonal matrix Q and an upper triangular matrix R.

Step-by-step explanation:

The QR decomposition of a matrix is a factorization of the matrix into an orthogonal matrix Q and an upper triangular matrix R. In MATLAB, this can be done using built-in functions or by implementing the Gram-Schmidt process algorithm, which seems to be the intention in the code snippet you provided. However, to make the provided algorithm work correctly, there are a few corrections needed:

Corrected Code for QR Decomposition

A = randi([-8, 8], 7, 5);
[m, n] = size(A);
Q = zeros(m, n);
R = zeros(n, n);

for j = 1:n
Q(:,j) = A(:,j);
for k = 1:j-1
R(k,j) = Q(:,k)' * A(:,j);
Q(:,j) = Q(:,j) - Q(:,k) * R(k,j);
end
R(j, j) = norm(Q(:, j));
Q(:, j) = Q(:, j) / R(j, j);
end

After running the corrected code, you will obtain the matrices Q and R that represent the QR decomposition of the matrix A. The matrix Q should be orthogonal, and R should be upper triangular. Remember to check that Q times R indeed gives the original matrix A.

Results

I cannot provide the exact Q and R matrices since the input matrix A is generated randomly. You will need to run the corrected MATLAB code on your computer to obtain these results.

User Charles Thayer
by
8.3k points