Page MenuHome

Change Matrix Representation and Access in Python to Conform with Standard Notation
Closed, ArchivedPublicPATCH

Description

It is often a point of confusion among new users that matrices don't appear to behave correctly within Blender. It is often cited that internally Blender stores matrices in column major format, while typically users are expecting row major format. However this does not fully explain the issues around matrices. For instance, if a user were to enter:

m=Matrix(((1, 2), (3, 4)))

They would receive the following upon inspecting m:

Matrix(((1.0, 2.0),
(3.0, 4.0)))

Which appears as expected and may be accessed as expected with m[row][column] notation. However, should a vector be entered, e.g.,

v=Vector((1, 1))

and then multiplied by the matrix, the incorrect result would be formed,

m*v == Vector((4.0, 6.0))

whereas the user would expect

m*v == Vector(( m[0][0] * v[0] + m[0][1] * v[1], m[1][0] * v[0] + m[1][1] * v[1] )) = Vector((3.0, 7.0))

This issue arises because the Python Representation -> Internal Data conversion is performed incorrectly for the representation shown in the console.

This patch rectifies the issue by ensuring that the conversion from Python representation to internal storage and back again accounts for the differing notations used by each. This also means that no internal functions for calulating matrix products, additions etc are modified, only the initialisation and representation of matrices in Python.

Thanks,
Andrew

Event Timeline

While using the patched matrices, an error in matrix/vector multiplication was uncovered for non-square matrices.

m = Matrix(((1, 1, 1), (2, 2, 2)))
v = Vector((1, 1, 1))

m * v == Vector((3.0, 6.0, -12289734))

This is because resultant vector was not being sized properly but merely taking its size from the input vector which is bad. It should have size == mat1->col_size

This needs fixing.

I don't think this reasoning is correct. Creating and printing matrices uses a list of columns. So the rows are (1, 3) and (2, 4), and a multiplication with vector (1, 1) gives (4, 6).

I've attached a new patch which accounts for recent changes in mathutils. This patch also rectifies the problem with matrix/vector multiplication noted above. In addition, it also wraps the translation component of a matrix into matrix.translation but only for 4x4 matrices. This is especially useful for scripts that originally used matrix[3] to access the translation component.

Thanks,
Andrew

Small fix for most recent SVN

Final patch which is separated from some fixes already applied by Campbell.

Campbell Barton (campbellbarton) changed the task status from Unknown Status to Unknown Status.Dec 22 2011, 6:48 AM