In
mathematics, a matrix is a rectangular array of numbers, symbols, or
expressions, arranged in rows and columns. You can create matrix in R using
matrix() function.
> matrix1 <- matrix(nrow=2, ncol=4) > matrix1 [,1] [,2] [,3] [,4] [1,] NA NA NA NA [2,] NA NA NA NA > > dim(matrix1) [1] 2 4 > > attributes(matrix1) $dim [1] 2 4
matrix1
<- matrix(nrow=2, ncol=4)
Above
statement creates a matrix with number of rows 2 and number of columns 4.
dim(matrix1)
dim function
returns the dimensions of given matrix.
Matrices in
R language are constructed in column-wise.
> matrix2 <- matrix(1:6, nrow=2, ncol=3) > matrix2 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
As you
observe above snippet, elements
1,2 are stored in column1
3,4 are stored in column2
5,6 are stored in column3
Accessing elements of Matrix
You can access elements of matrix using
“matrixName[row, column]”.> matrix2[1,1] [1] 1 > matrix2[1,2] [1] 3 > matrix2[1,3] [1] 5 > matrix2[2,1] [1] 2 > matrix2[2,2] [1] 4 > matrix2[2,3] [1] 6
In the same
you access elements, you can assign values to matrices.
> matrix2[1,1]<-100 > matrix2 [,1] [,2] [,3] [1,] 100 3 5 [2,] 2 4 6
Get the transpose of a matrix
You can get the transpose of a matrix by using
t() function.> matrix2 [,1] [,2] [,3] [1,] 100 3 5 [2,] 2 4 6 > > matrix3 = t(matrix2) > > matrix3 [,1] [,2] [1,] 100 2 [2,] 3 4 [3,] 5 6
Deconstruct matrix
You can
deconstruct matrix by using c() function.
> matrix3 [,1] [,2] [1,] 100 2 [2,] 3 4 [3,] 5 6 > > c(matrix3) [1] 100 3 5 2 4 6
No comments:
Post a Comment