swaffelay
swaffelay

Reputation: 323

best matrix full of same number

I would like to create a n x n matrix with n being a large number, what is the fastest way to do this in sage ?

I would like a matrix like for example n = 3 == [(3,3,3)(3,3,3),(3,3,3)]

I currently do this with ones_matrix(n) * somenumber

However this takes a while with a big n, is there a faster way to do this in sage?

Thx for helping

Upvotes: 0

Views: 104

Answers (3)

John Palmieri
John Palmieri

Reputation: 1696

If you want to work with Sage matrices, you can do this:

sage: M = MatrixSpace(ZZ, 10000, 10000)
sage: a = M.matrix([3]*10000*10000)

On my computer, this takes about 6 seconds, the same time as ones_matrix(10000), faster than 3 * ones_matrix(10000). Not nearly as fast as the numpy solution, but then the result is a Sage matrix. Note that if you want to work with noninteger entries, you should change the ZZ to the appropriate ring.

Upvotes: 1

Anwarvic
Anwarvic

Reputation: 12992

You can use the numpy.full() function like so:

>>> import numpy as np
>>> arr = np.full((3, 3), 3)
>>> arr
[[3 3 3]
 [3 3 3]
 [3 3 3]]
>>> arr2 = np.full((3, 3), 7)
>>> arr2
[[7 7 7]
 [7 7 7]
 [7 7 7]]

Upvotes: 1

Bully Maguire
Bully Maguire

Reputation: 211

A shortcut way would be:

n=int(input())
tup=tuple((n,))*n
#gives (n,n,n,...…,n) n times

ar=list((tup,)*n)
#would give ar=[(n,n,.....,n),(n,n,n,.....,n),...…..(n,n,n,...…,n)]

or doing in a single stroke: ar=list((tuple((n,))*n,)*n)

Upvotes: 1

Related Questions