Multidimensional character matrix in Python

I would like to create a 3D matrix of a certain size by calculating the value for each combination of indices. Each value in the matrix will be symbolic.

What I have tried so far:

import numpy as np import sympy as sp var1 = np.arange(1,10,2) var2 = np.arange(1,10,2) var3 = np.arange(20,50,5) myMatrix = np.zeros(shape = (len(var1), len(var2), len(var3))) t = sp.symbols('t') for ii in range(len(var1)): for jj in range(len(var2)): for kk in range(len(var3)): myMatrix[ii][jj][kk] = var1[ii] * var2[jj] * var3[kk] * t 

This gives me an error:

TypeError: cannot convert expression to float

as I understand it, due to the union of numpy and sympy. So I tried:

 myMatrix = sp.MatrixSymbol('temp', len(var1), len(var2), len(var3)) 

instead:

 myMatrix = np.zeros(shape = (len(var1), len(var2), len(var3))) 

and received an error message:

TypeError: new () takes exactly 4 arguments (5 data)

To summarize, I ask the question: how can I create a 3D matrix with any variables inside to be able to use it in a nested loop that involves a symbolic calculation?

(This is my first post in this community, so please let me know if I did something wrong.)

+5
source share
1 answer

The first error you get, as you suggested, is an attempt to save an object of type sympy to a numpy array of zeros that has type numbers. One option is to use a numpy array, which works as follows:

 import numpy as np import sympy as sp var1 = np.arange(1,10,2) var2 = np.arange(1,10,2) var3 = np.arange(20,50,5) myMatrix = np.empty((len(var1), len(var2), len(var3)), dtype=object) t = sp.symbols('t') for ii in range(len(var1)): for jj in range(len(var2)): for kk in range(len(var3)): myMatrix[ii][jj][kk] = var1[ii] * var2[jj] * var3[kk] * t 

Although for large sizes this is not too efficient, and not the way numpy works. However, for sympy arrays this may be the only way, since it seems that, at least in my version of sympy (0.7.1.rc1), 3D arrays are not supported. For

 myMatrix = sp.zeros((len(var1), len(var2), len(var3))) 

I get the following error

 ValueError: Matrix dimensions should be a two-element tuple of ints or a single int! 
+3
source

Source: https://habr.com/ru/post/1244039/


All Articles