R Matrices

Matrices are the R-objects, in which the two-dimensional rectangular data set are arranged. A matrix can be built using the matrix() function.

Syntax:

Where, data: – it is the input vector will be the data elements of the matrix

nrow: –  number of rows to be created

ncol:  number of columns to be created

byrow: – it is just a logical clue. If it is TRUE then the input vector elements are arranged by row.

dimname: – it is the names assigned to the rows and columns.

Example 1:

Output:

Example 2:

Output:

Example 3:

Output:

Accessing elements of a Matrix

We can access the elements of a matrix by using the column and row index of the element.

Example:

Output:

Modifying Element of a Matrix

To modify the elements of a matrix we just need to assign the value through the assignment operator in the index of the value.

Example:

Output:

Adding Row or Column in the Matrix

We can add a row or column in the matrix using rbind() and cbind() function respectively.

Example:

Output:

Changing Dimension of a Matrix

We can change the dimension of a matrix through the dim() function.

Example:

Output:

Transpose a Matrix

We can transpose a matrix in R with the function t().

Example:

Output:  

Matrix Computations

In R, we can perform various mathematical operations on the matrices using the R operators. The result of the operation is also a matrix.

To perform the operation, the dimension should be the same for the matrices.

Matrix Addition and Subtraction

Example:

Output:

Matrix Division

Example:

Output:

Matrix Multiplication

Example:

Output:

When you change the order of the multiplication the result will be different. It means AB is not equal to BA.

Example:

Output:

Reference:
https://www.datamentor.io/r-programming/matrix/
https://www.tutorialspoint.com/r/r_matrices.htm