R(14), Matrix

Published: by Creative Commons Licence

A Matrix is an R object in which elements are laid out in a two-dimensional rectangular layout, they contain elements of the same atomic type.

We use a matrix containing numeric elements for mathematical calculations.

if you wanna see the examples of the following functions, click here please.

How to Create

We use the function matrix() to create a matrix.

matrix(data, nrow, ncol, byrow, dimnames)
  • data: the inputs of the numeric elements in vector
  • nrow: the number of rows to create
  • ncol: the number of column to create
  • byrow: if the value is TRUE, then the input elements will be arranged in rows.
  • dimnames: the names assigned to the row and column

How to Visit

use the index of row and column

Calculate

When using R operators to perform various mathematical operations, the results of the operations should also be matrix.

Also, for the matrix involved in the operation, the dimensions(number of rows and columns) should be the same.

When using * and /, the elements of the two matrices with the same position will carry out the corresponding operation.

# 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)

# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","
")
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 multiplication 
    [,1] [,2] [,3]
[1,]   15    0    6
[2,]   18   36   24