How to multiply vector4 with matrix4x4 in Unity?

Hello guys!

If I would like to multiply a Vector4 with a Matrix4x4, what method can I use? I have only found Matrix4x4.MultiplyVector(), but as far as I understand this is for multiplying a matrix with a vector and this type of multiplication is not commutative.

Actually I am looking for the equivalent forms of XMVector3Transform and XMVector3TransformCoord.

Matrix vector multiplication in Unity can only be done this way. Matrices act like functions on the vector and are applied right to left. So the classical MVP matrix (combined modelview, view and projection matrix) are applied (P * V * M) * v. So vectors are always treated as column vectors / matrices.

As you hopefully know, when you want to do the opposite, you can take the transpose of the matrix. So if you want to do v * M you can do M.transpose * v to get the same result.

So you should ask yourself how you want to interpret your vector, as row or column vector. If you want to represent it as row vector, you can only multiply it on the left of the matrix. If you want to use it as a column vector (which is the default in Unity and most other graphics APIs as well as the usual definition of the matrix-vector multiplication), you can only multiply it on the right of the matrix. There is no other way as any other interpretation would not allow to multiply them at all.

In general, in order to multiply two matrices, the column count of the left matrix has to match the row count of the right one. The resulting matrix has as many rows as the first matrix and as many columns as the second matrix. So

AxB * CxD = AxD (B and C have to be the same numbers or you can’t multiply them)

So if AxB should be a vector, it has to be a row vector (1x4). Multiplying with a 4x4 matrix would result in a 4x1 column vector. However in Unity you can only do it the other way round. So vectors are always treated as column vector. So you can only do it this way:
(4x4) * (4x1)

As I said v * M with v as row vector would be the same as Mt * v with v as column vector.

See this example:

(x,y) * [A B] == (x*A + y*C)
        [C D]    (x*B + y*D)

// lets transpose the matrix and multiply on the right:
[A C] * (x) == (A*x + C*y, B*x + D*y)
[B D]   (y)

As you can see, you get the same result. The question is what you actually want to do. The documentation of XMVector3TransformCoord is not very specific what it actually does. Applying a matrix to a vector usually applies it on the left side of the vector. That’s the usual convention in almost all systems.