R类型3R语言矩阵

1R语言矩阵

 我们使用包含数字元素的矩阵用于数学计算。

使用matrix()函数创建一个矩阵。matrix(data, nrow, ncol, byrow, dimnames)

以下是所使用的参数的说明 -

  • 数据是成为矩阵的数据元素的输入向量。
  • nrow是要创建的行数。
  • ncol是要创建的列数。
  • byrow是一个逻辑线索。 如果为TRUE,则输入向量元素按行排列。
  • dimname是分配给行和列的名称

M <- matrix(c(3:14), nrow = 4, byrow = TRUE)//如果为TRUE,则输入向量元素按行排列。

print(M)

N <- matrix(c(3:14), nrow = 4, byrow = FALSE)  //默认情况是这样的

print(N)

     [,1] [,2] [,3]

[1,]    3    4    5

[2,]    6    7    8

[3,]    9   10   11

[4,]   12   13   14

     [,1] [,2] [,3]

[1,]    3    7   11

[2,]    4    8   12

[3,]    5    9   13

[4,]    6   10   14

 

 

列分配给行和列的名称

# Define the column and row names.

rownames = c("row1", "row2", "row3", "row4")

colnames = c("col1", "col2", "col3")

 

P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))

print(P)

  col1 col2 col3

row1    3    4    5

row2    6    7    8

row3    9   10   11

row4   12   13   14

2访问矩阵的元素

# Access the element at 3rd column and 1st row.  (顺序是y,x)

print(P[1,3])

 

# Access the element at 2nd column and 4th row.  

print(P[4,2])

 

# Access only the  2nd row.

print(P[2,])

 

# Access only the 3rd column.

print(P[,3])

 

[1] 5

[1] 13

col1 col2 col3 

   6    7    8 

row1 row2 row3 row4 

   5    8   11   14 

3矩阵计算

使用R运算符对矩阵执行各种数学运算。 操作的结果也是一个矩阵。

对于操作中涉及的矩阵,维度(行数和列数)应该相同。

矩阵加法和减法

# Create two 2x3 matrices.

matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)

print(matrix1)

 

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)

print(matrix2)

 

# Add the matrices.

result <- matrix1 + matrix2

cat("Result of addition","

")

print(result)

 

# Subtract the matrices

result <- matrix1 - matrix2

cat("Result of subtraction","

")

print(result)

    [,1] [,2] [,3]

[1,]    3   -1    2

[2,]    9    4    6

     [,1] [,2] [,3]

[1,]    5    0    3

[2,]    2    9    4

Result of addition 

     [,1] [,2] [,3]

[1,]    8   -1    5

[2,]   11   13   10

Result of subtraction 

     [,1] [,2] [,3]

[1,]   -2   -1   -1

[2,]    7   -5    2

# Multiply the matrices.

result <- matrix1 * matrix2

cat("Result of multiplication","

")

print(result)

 

# Divide the matrices

result <- matrix1 / matrix2

cat("Result of division","

")

print(result)

Result of multiplication 

     [,1] [,2] [,3]

[1,]   15    0    6

[2,]   18   36   24

Result of division 

     [,1]      [,2]      [,3]

[1,]  0.6      -Inf 0.6666667

[2,]  4.5 0.4444444 1.5000000

 

posted @ 2017-12-04 09:53  克维拉  阅读(865)  评论(0编辑  收藏  举报