# Resize a matrix

27 views

### Yeti

Nov 2, 2018, 5:33:47 AM11/2/18
to mpmath
This might seem a very stupid question, but is there an inbuilt means to change the dimensions of a matrix? Say I have a 9 x 1 matrix, can mpmath reshape that to a 3 x 3 matrix?

The documentation mentions that the dimensions of an existing matrix can be changed using the .rows and .columns commands, but this creates new matrix elements of zeros and discards the rest of the data.

One way I have used is to convert the mp.matrix to a numpy object array, reshape, then transform back to an mp.matrix, but I am finding that sometimes numbers are being truncated back down to double precision which then breaks the arbitrary precision of the code.

Does anyone have any tips on how to do this process fast within mpmath?

Many thanks

### Samuel Lelièvre

Nov 23, 2018, 6:32:54 PM11/23/18
to mpmath
Fri 2018-11-02 10:33:47 UTC+1, Yeti:
>
> is there an inbuilt means to change the dimensions of a matrix?
> Say I have a 9 x 1 matrix, can mpmath reshape that to a 3 x 3 matrix?

There does not seem to be a built-in function for that.
Below is an example and a helper function based on it.

Example of converting a 4 by 1 matrix into a 2 by 2 one.

Imports and settings:

>>> from mpmath import *
>>> mp.dps = 15
>>> mp.pretty = True

Define a:

>>> a = matrix(list(range(4)))
>>> a
[0.0]
[1.0]
[2.0]
[3.0]

Turn it into a list and flatten the list:

>>> b = sum(a.tolist(), [])
>>> b
[0.0, 1.0, 2.0, 3.0]

Use that list to build the new matrix:

>>> c = matrix([b[2*k:2*k+2] for k in range(2)])
>>> c
[0.0  1.0]
[2.0  3.0]

Helper function to reshape any matrix to any size:

>>> def reshape(mat, m, n):
...     z = sum(mat.tolist(), [])
...     return matrix([z[n*k:n*k+n] for k in range(m)])
...
>>> d = matrix(list(range(9)))
>>> reshape(d, 3, 3)
[0.0  1.0  2.0]
[3.0  4.0  5.0]
[6.0  7.0  8.0]