u <- matrix(c(.5, .5), ncol = 1)
v <- matrix(c(3, -4), ncol = 1)
\(\begin{bmatrix} .5 \\ .5 \end{bmatrix}\cdot \begin{bmatrix} 3 \\ -4 \end{bmatrix}\)
\(=.5\times 3+.5\times -4\)
Or less manually:
t(u)%*%v
## [,1]
## [1,] -0.5
\(\left\| u \right\| \quad =\quad \sqrt { { .5 }^{ 2 }+\sqrt { { .5 }^{ 2 } } }\)
\(=\)
norm(u, type = "f")
## [1] 0.7071068
\(\left\| v \right\| \quad =\quad \sqrt { { 3 }^{ 2 }+\sqrt { { -4 }^{ 2 } } }\)
\(=\)
norm(v, type = "f")
## [1] 5
\(3u-2v\)
\(=3\ast \begin{bmatrix} .5 \\ .5 \end{bmatrix}-2\ast \begin{bmatrix} 3 \\ -4 \end{bmatrix}\)
\(=\begin{bmatrix} 3*.5 \\ 3*.5 \end{bmatrix}-\begin{bmatrix} 2*3 \\ 2*-4 \end{bmatrix}\)
\(=\)
3*u - 2*v
## [,1]
## [1,] -4.5
## [2,] 9.5
\(\cos { \alpha } =\frac { u\bullet v }{ \left\| u \right\| \ast \left\| v \right\| }\)
\(\cos { \alpha } =\frac { -.5 }{ 5*\sqrt { .5 } }\)
\(\cos { \alpha } =-.1414\)
\(\alpha =\)
rs <- (t(u)%*%v)/(norm(v, type = "f") * norm(u, type = "f"))
acos(rs)
## [,1]
## [1,] 1.712693
(answer in radians)
Warning: Do not trust the solution set for an inconsistent system Free variables are assumed to be 0 for solutions to non-square matrices
gauss.jordan <- function(matrix, vector){
library(tidyverse)
rref <- cbind(matrix, vector)
rows <- nrow(rref)
cols <- ncol(rref)
zero_piv <- F
r <- 1
for (j in 1:cols){
if(r > rows){
break
}
if (all(near(rref[r,], 0))){
zero_piv <- T
break
}
for (i in r:rows){
#find the first nonzero row in the current column
if (!near(rref[i,j], 0)){
#create the leading 1, then swap rows
temp_row <- rref[i, ]/rref[i,j]
rref[i,] <- rref[r,]
rref[r,] <- temp_row
}
#Vectorized version of row operations
#Copy the temp_row for each row you need to perform the operation on, then
#scale it by the entry in column J for that row
rref[c(1:rows) != r, ] <- rref[c(1:rows) != r, ] -
matrix(rep(temp_row, each = rows - 1), ncol = cols, nrow = rows - 1) * rref[c(1:rows) != r, j]
}
r <- r + 1
}
solution_set <- rref[1:min(cols-1,rows), cols]
if (zero_piv == F){
print("Solution:")
print(round(solution_set, 3))
}
else{
print("Warning: Singular Matrix")
print("One of the infinite possible solutions:")
print(solution_set)
}
return(list(rref, solution_set))
}
Test out the function on sample Matrix:
A <- matrix(c(1,2,-1, 1,-1,-2,3,5,4), nrow = 3, ncol = 3)
v<- c(1,2,6)
gauss.jordan(A,v)
## [1] "Solution:"
## [1] -1.545 -0.318 0.955
## [[1]]
## vector
## [1,] 1 0 0 -1.5454545
## [2,] 0 1 0 -0.3181818
## [3,] 0 0 1 0.9545455
##
## [[2]]
## [1] -1.5454545 -0.3181818 0.9545455
Test on matrix with more variables than equations
A <- matrix(c(1,2,1,-1,1,1,3,7), nrow = 2, ncol = 4)
v <- c(1,8)
gauss.jordan(A,v)
## [1] "Solution:"
## [1] 3 -2
## [[1]]
## vector
## [1,] 1 0 0.6666667 3.3333333 3
## [2,] 0 1 0.3333333 -0.3333333 -2
##
## [[2]]
## [1] 3 -2