Learning language scratch R (c) - "Matrix (the Matrix)" Data Structure

This article first to know almost Column: https://zhuanlan.zhihu.com/p/60140022

Also simultaneously updated on my personal blog: https://www.nickwu.cn/blog/id=129


 3. [dimensional]: matrix (the Matrix)

3.1 Creating a matrix

m <- c(45,23,66,77,33,44,56,12,78,23)
dim (m) <- c (2,5) # 2 to create a matrix of rows and five columns, are arranged in top to bottom, from left to right in the order
# Output: [1] [2] [3] [4] [5]
 [1,]   45   66   33   56   78
 [2,]   23   77   44   12   23
# May be used m [1,2] or m [1,] and other forms are indexed
m <- matrix (c (45,23,66,77,33,44,56,12,78,23), 2,5) # just like the one kind
m <- matrix (c (45,23,66,77,33,44,56,12,78,23), 2,5, byrow = TRUE) # just like the one of which is equal to TRUE byrow default, may be omitted. To FALSE if the press columns.
 
m <- matrix(c(45,23,66,77,33,44,56,12,78,23),2,5,byrow=FALSE) 
# Output: [1] [2] [3] [4] [5]
 [1,]   45   66   33   56   78
 [2,]   23   77   44   12   23

3.2 Matrix Index

results <- matrix(c(10,30,40,50,43,56,21,30),2,4,byrow=TRUE)
colnames (results) <- c ( '1qrt', '2qrt', '3qrt', '4qrt') # may utilize colnames () of the column of the matrix named
rownames (results) <- c ( 'store1', 'store2') # may utilize rownames () named row matrix
results [ 'store1',] # matrix can be indexed by a row or column name
results['store2',c('1qrt','4qrt')]

3.3 transposed matrix

T () function can be transposed matrix

3.4 Digital and matrix multiplication

And a number matrix multiplication, the matrix is ​​multiplied with each element

m <- matrix(c(1,4,2,5,3,6),2,3)
m*3
# Output:
       [,1] [,2] [,3]
 [1,]    3    6    9
 [2,]   12   15   18

3.5 Matrix addition

Consistent with the mathematical rules, the position of the matrix elements corresponding to the addition i.e. adding

3.6 Matrix multiplication

Matrix multiplication with m1% *% m2 (Note: Be sure to meet the mathematical matrix multiplication rule)

m1 <- matrix(c(1,1,1,1,1,1,1,1,1),3,3)
m2 <- matrix(c(1,0,0,0,1,0),3,2)
m1 %*% m2
# Output:
       [,1] [,2]
 [1,]    1    2
 [2,]    1    2
 [3,]    1    2
# Note, m2% *% m1 meaningless, because they do not conform to the rules of matrix multiplication, to make it set up, need to be transposed matrix

Cbind 3.7 using () or of rbind () the vectors and matrices into a

m1 <- matrix(c(45,23,66,77,33,44,56,12,78,23),2,5)
m1
cbind(c(4,76),m1[,4])
# Output: [1] [2]
[1,]    4   56
[2,]   76   12
# Prompt, cbind () is connected to the lateral vector and matrix (in ways)
​
m2 <- matrix(rep(10,20),4,5)
m2
m3 <- rbind (m1 [1,], m2 [3,])
# Output: [1] [2] [3] [4] [5]
[1,]   45   66   33   56   78
[2,]   10   10   10   10   10
Tip #: rbind () is similar, but the longitudinal connection (according to line mode)

Guess you like

Origin www.cnblogs.com/nickwu/p/12567139.html