Orthogonalize It

As discussed in Lab 3, it is often advantageous to construct orthogonal matrices spanning the same column space as a design matrix of interest. The purpose of this challenge is to explore fast techniques for doing so. While challenge 4 will ask you to perform Graham Schmidt orthogonalization for large data sets, requiring some careful thought about memory management, the purpose of this exercise is simply to be fast. Efficient code tends to be particularly critical in a few situations:

If, for example, you need to perform an orthogonalization step inside a loop for a simulation, or as part of a Bayesian sampling algorithm, optimizing this functon could be of critical importance.

Challenge

Your task is to create a function called MGS which accepts an argument x, which is assumed to be an \(n\times p\) matrix to be orthogonalized. It should apply the modified Graham-Schmidt algorithm to x, and return the result. As before, the machine on which the code will be run is a 4 core Ubuntu 16.04 virtual server with 8 GB of RAM and 20 GB of hard disk space. The code will be run on a variety of matrices, but you may assume that the matrices have no problem fitting into the available RAM.

Note: with some of these matrix decomposition and orthogonalization problems, different algorithms will provide the same orthonormal structure, but columns will be differently scaled by 1 or -1. This is OK for our purposes, because we generally care about the column space and the orthogonality for these problems