# [Numpy-discussion] Automatic matrices

Paulo Jose da Silva e Silva pjssilva at ime.usp.br
Fri Dec 15 07:27:21 CST 2006

```Hello,

If a numpy user is specially concerned with numerical linear algebra (or
more generally with Math), it may find unconvenient the use of the dot
function instead of the * operator. This behavior may be specially
unpleasant for someone migrating from Matlab.

I believe that this is the may reason for the existence of the matrix
class within numpy.

However, after trying to use the matrix class I have came across a major
roadblock: many numpy/scipy functions return an array by default and not
matrices. Then, we need then to add many conversion calls to the 'mat'
function in our code. This is also unconvenient.

I have had the idea of trying to write some code to automatically call
the mat function for me. I have a very simple and inefficient prototype

http://www.ime.usp.br/~pjssilva/matrix_import.py

The use is simple. Instead of importing a numerical module with import,
use the special class MatrixfiedModule from the above file. Let me give
an example:

--- ipython session ---

In [2]:import matrix_import as mi

In [3]:num = mi.MatrixfiedModule('numpy')
Importing numpy

In [4]:la = mi.MatrixfiedModule('scipy.linalg')
Importing scipy.linalg

In [5]:A = num.random.rand(3,4)
Importing numpy.random

In [6]:Q, R = la.qr(A)

In [7]:la.norm(Q*R - A)
Out[7]:6.0555516793379748e-16

----- End session -----

For now the solution is very inefficient: every function call to a
MatrixfiedModule function is wrapped on the fly to search for array
return values ad convert them to matrix. This can certainly be improved
the wrapping all the functions in the original module first. I plan to

It is also incomplete: The automatic conversion only happens for return
values of module function. It doesn't try to deal with special objects
like  finfo(float).eps or mgrid[0:9.,0:6.]. I am not sure how to deal
with this.

I can donate the code to scipy if there is any interest. Any comments?

Best,

Paulo

--
Paulo José da Silva e Silva
Professor Assistente, Dep. de Ciência da Computação
(Assistant Professor, Computer Science Dept.)
Universidade de São Paulo - Brazil

e-mail: pjssilva at ime.usp.br        Web: http://www.ime.usp.br/~pjssilva

Teoria é o que não entendemos o    (Theory is something we don't)
suficiente para chamar de prática. (understand well enough to call)
(practice)

```