defining matrices of indeterminates

7 views
Skip to first unread message

Robin Whitty

unread,
Aug 4, 2010, 6:23:18 PM8/4/10
to sympy
Is there a way to define a matrix of indeterminates in SymPy? In
Maple, for instance, the definition
a:=matrix(3,3);
gives you 9 indeterminates a[1,1],...,a[3,3].

Thanks

Robin

Bastian Weber

unread,
Aug 4, 2010, 7:41:01 PM8/4/10
to sy...@googlegroups.com
Hi Robin


maybe this serves for you:


def symbMatrix(n, m, s='a'):
A = sp.Matrix(n,m, lambda i,j:sp.Symbol( s+'%i%i'%(i+1,j+1)) )
return A


Regards,

Bastian

Aaron S. Meurer

unread,
Aug 4, 2010, 7:42:12 PM8/4/10
to sy...@googlegroups.com
I think this is the easiest way to do it:

In [15]: Matrix(3, 3, lambda i, j: Symbol('a%d%d' % (i, j)))
Out[15]:
⎡a₀₀ a₀₁ a₀₂⎤
⎢ ⎥
⎢a₁₀ a₁₁ a₁₂⎥
⎢ ⎥
⎣a₂₀ a₂₁ a₂₂⎦

The third argument to Matrix is a 2 argument lambda function that generates Symbols named ai,j, where i, j is the index of the element. Note that the indices start at 0. You can use any function as the second arg, and it will just plug in the row, col of each element.

If you also want those symbols in your namespace, you can do

In [16]: var(['a%d%d' % (i, j) for i in range(3) for j in range(3)])
Out[16]: [a₀₀, a₀₁, a₀₂, a₁₀, a₁₁, a₁₂, a₂₀, a₂₁, a₂₂]

Aaron Meurer

Ondrej Certik

unread,
Aug 4, 2010, 8:27:10 PM8/4/10
to sy...@googlegroups.com
On Wed, Aug 4, 2010 at 4:42 PM, Aaron S. Meurer <asme...@gmail.com> wrote:
> I think this is the easiest way to do it:
>
> In [15]: Matrix(3, 3, lambda i, j: Symbol('a%d%d' % (i, j)))
> Out[15]:
> ⎡a₀₀  a₀₁  a₀₂⎤
> ⎢             ⎥
> ⎢a₁₀  a₁₁  a₁₂⎥
> ⎢             ⎥
> ⎣a₂₀  a₂₁  a₂₂⎦

Actually, the fastest way is to use symarray:

In [1]: symarray("a", (3, 3))
Out[1]:
[[a_0_0 a_0_1 a_0_2]
[a_1_0 a_1_1 a_1_2]
[a_2_0 a_2_1 a_2_2]]

In [2]: Matrix(symarray("a", (3, 3)))
Out[2]:


⎡a₀ ₀ a₀ ₁ a₀ ₂⎤
⎢ ⎥
⎢a₁ ₀ a₁ ₁ a₁ ₂⎥
⎢ ⎥
⎣a₂ ₀ a₂ ₁ a₂ ₂⎦

Ondrej

Reply all
Reply to author
Forward
0 new messages