Creating Matrices with matrix()
Build matrices by specifying data, nrow, ncol, and byrow.
What is a Matrix in R?
A matrix in R is a two-dimensional data structure where all elements must be of the same type. Think of it as a table with rows and columns. Matrices are essential for linear algebra, image processing, and statistical computations.
# A simple 2x3 matrix
m <- matrix(1:6, nrow = 2, ncol = 3)
cat('A 2x3 matrix:
')
print(m)
cat('Dimensions:', dim(m), '
') # rows colsmatrix(data, nrow, ncol)
The matrix() function takes a vector of data and arranges it into rows and columns. By default, R fills the matrix column by column (column-major order).
# Filled column by column (default)
m_col <- matrix(1:12, nrow = 3, ncol = 4)
cat('Column-filled 3x4 matrix:
')
print(m_col)
cat('Note: 1,2,3 fill the first COLUMN, not the first row
')All lessons in this course
- Creating Matrices with matrix()
- Matrix Indexing and Subsetting
- Matrix Arithmetic and Operations
- Transposing and Reshaping Matrices