There are some differences between tha MATLAB and the R version of diag.
Specifically, if a 1xN or a Nx1 matrix is supplied to the R
diag
function then just the first element of this vector is
returned. This function tries to match the MATLAB version in handling vectors
(matricies with one dimension equal to one), and will return a diagonal
matrix in these situations.
Examples
diag_matlab(3)
#> [,1] [,2] [,3]
#> [1,] 1 0 0
#> [2,] 0 1 0
#> [3,] 0 0 1
diag_matlab(c(1,2,3))
#> [,1] [,2] [,3]
#> [1,] 1 0 0
#> [2,] 0 2 0
#> [3,] 0 0 3
diag_matlab(cbind(1,2,3))
#> [,1] [,2] [,3]
#> [1,] 1 0 0
#> [2,] 0 2 0
#> [3,] 0 0 3
diag_matlab(rbind(1,2,3))
#> [,1] [,2] [,3]
#> [1,] 1 0 0
#> [2,] 0 2 0
#> [3,] 0 0 3
diag_matlab(matrix(c(1, 2, 3),6,6))
#> [1] 1 2 3 1 2 3
# here is where the R default does something different
diag(cbind(1,2,3))
#> [1] 1
diag(rbind(1,2,3))
#> [1] 1