Why is multiplying a matrix which col # doesn't match a vector length allowed?

My course text includes

mat<-matrix(data = 1:12, nrow = 3, ncol = 4, byrow = TRUE)
vecteur <- c(2, 4, 5)
vecteur%*%mat

outputting

C1 C2 C3 C4
[1,] 67 78 89 100

To help visualize the matrix, here's its output:

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

[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12

As you can see mat has ncol = 4 and vecteur has a length of 3. I thought from mathematics the # of columns of the matrix needed to match the # of rows of a vector in order for the multiplication to take place. There's another instance of the same phenomenon on Multiply Matrix by Vector in R - GeeksforGeeks

Would someone explain to me how I'm either misunderstanding the mathematical principal or how R handles the non-mathematical multiplication of a matrix by a vector?

Thank you kindly

In your example, vecteur is a 1 x 3 matrix (row vector) and mat is 3 x 4, so the product is well defined both mathematically and in R. What happens if you reverse the order of multiplication?

1 Like

It seems my brain inverted the multiplication because I had only seen matrices multiplied by vectors. It seems it uses the matrices multiplied by matrices formula with the 1st matrix of a 1-column variety.
My verification:

> mat[, 1]
[1] 1 5 9
*(2, 4, 5)
,
> mat[, 2]
[1]  2  6 10
*(2, 4, 5)
,
> mat[, 3]
[1]  3  7 11
*(2, 4, 5)
,
> mat[, 4]
[1]  4  8 12
*(2, 4, 5)
=
> mat[, 1]
1*2+5*4+9*5
,
> mat[, 2]
2*2+6*4+10*5
,
> mat[, 3]
3*2+7*4+11* 5
,
> mat[, 4]
4*2+8*4+12*5
=
67, 78, 89, 100

Yes, the definition of multiplication by a matrix (in both mathematics and R), uses the matrix-matrix multiplication algorithm. This requires that a vector be interpreted as a one-row or one-column matrix, depending on the order of multiplication, and that number of columns of the left matrix equal the number of rows of the right matrix.

1 Like

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.