Module 5: Matrix Algebra in R
GitHub Link: r-programming-assignments/Assignment_05.R at main · AustinTCurtis/r-programming-assignments
On your blog, include:
- R code for creating A and B, and for computing
invA,detA,invB, anddetB. - Output or error messages for each operation.
- A brief explanation:
- Why
solve(A)anddet(A)work. - Why operations on B fail (non‑square matrix).
- Any notes on numeric stability or performance.
R Code:
> # Create matrices
> A <- matrix(1:100, nrow = 10) # 10 x 10> B <- matrix(1:1000, nrow = 10) # 10 x 100>> #Inspect Dimension> cat("dim(A): ", paste(dim(A), collapse = " x "), "\n") # expected 10 x 10dim(A): 10 x 10> cat("dim(B): ", paste(dim(B), collapse = " x "), "\n") # expected 10 x 100dim(B): 10 x 100>> is_square <- function(M) { d <- dim(M); d[1] == d[2] }> cat("Is A square? ", is_square(A), "\n")Is A square? TRUE> cat("Is B square? ", is_square(B), "\n")Is B square? FALSE>> #Compute Inverses/Determinants> # For A> detA <- det(A) # determinant> invA <- tryCatch(solve(A), # inverse+ error = function(e) e)>> # For B> detB <- tryCatch(det(B),+ error = function(e) e)>> invB <- tryCatch(solve(B),+ error = function(e) e)>> #Print results> cat("det(A):\n"); print(detA)det(A):[1] 0> cat("\ninvA:\n"); print(invA)invA: <simpleError in solve.default(A): Lapack routine dgesv: system is exactly singular: U[6,6] = 0>>> cat("\nAttempt det(B):\n"); print(detB)Attempt det(B): <simpleError in determinant.matrix(x, logarithm = TRUE, ...): 'x' must be a square matrix>> cat("\nAttempt inv(B):\n"); print(invB)Attempt inv(B):<simpleError in solve.default(B): 'a' (10 x 100) must be square>
Explanation:
- Matrix A:
A is a 10×10 square matrix, so in principle det() and solve() apply.
The determinant is exactly 0, which means the matrix is singular (its columns are linearly dependent)
Because of this, solve(A) fails with a singularity error, there is no inverse
Matrix B:
B is 10×100, not square. Determinants and inverses are defined only for square matrices, so both det(B) and solve(B) fail immediately.
Numeric stability & performance notes:
It’s generally better to solve linear systems with solve (A, B) rather than computing the full inverse.
In practice, even for square matrices with very small determinants, solve() may become numerically unstable.
Comments
Post a Comment