One error message you may encounter when using R is:
Error in matrix2 %*% matrix1 : non-conformable arguments
This error occurs when you attempt to multiply two matrices but the number of columns in the left matrix does not match the number of rows in the right matrix.
The following example shows how to resolve this error in practice.
How to Reproduce the Error
Suppose we have the following two matrices in R:
#create first matrix
mat1 <- matrix(1:10, nrow=5)
mat1
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
#create second matrix
mat2 <- matrix(1:6, nrow=2)
mat2
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Now suppose we attempt to multiply the second matrix by the first matrix:
#attempt to multiply second matrix by first matrix
mat2 %*% mat1
Error in mat2 %*% mat1 : non-conformable arguments
We receive an error because the number of columns (3) in the left matrix does not match the number of rows (5) in the right matrix.
How to Avoid the Error
To avoid the non-conformable arguments error, we must instead multiply the first matrix by the second matrix:
multiply first matrix by second matrix
mat1 %*% mat2
[,1] [,2] [,3]
[1,] 13 27 41
[2,] 16 34 52
[3,] 19 41 63
[4,] 22 48 74
[5,] 25 55 85
Notice that we’re able to successfully multiply the two matrices without any error because the number of columns (2) in the left matrix matches the number of rows (2) in the right matrix.
We can also use the dim() function to display the number of columns and rows in each matrix:
#view dimensions of first matrix
dim(mat1)
[1] 5 2
#view dimensions of second matrix
dim(mat2)
[1] 2 3
From this output we can see:
- The first matrix has 5 rows and 2 columns.
- The second matrix has 2 rows and 3 columns.
This makes it obvious that we must use the first matrix on the left and the second matrix on the right when multiplying since the first matrix has 2 columns and the second matrix has 2 rows.
Additional Resources
The following tutorials explain how to fix other common errors in R: