ASKSAGE: Sage Q&A Forum - Latest question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Fri, 08 Feb 2019 13:40:39 -0600Is there an easy way to get the matrix of coefficients from a product of a matrix and a vector?http://ask.sagemath.org/question/45376/is-there-an-easy-way-to-get-the-matrix-of-coefficients-from-a-product-of-a-matrix-and-a-vector/I have a matrix multiplication of the form
$$ B = A x $$
or
$$
\begin{pmatrix} a_{11} x_1 + a_{12} x_2 + a_{13} x_3 \\\ a_{21} x_1 + a_{22} x_2 + a_{23} x_3 \\\ a_{31} x_1 + a_{32} x_2 + a_{33} x_3 \end{pmatrix} = \begin{pmatrix}
a_{11} & a_{12} & a_{13}\\\
a_{21} & a_{22} & a_{23}\\\
a_{31} & a_{32} & a_{33}
\end{pmatrix}
\cdot
\begin{pmatrix}
x_1 \\\
x_2 \\\
x_3
\end{pmatrix}
$$
Is there a way in Sage to factor $B$ in a way where I give it $x$ and it returns $A$?
Edited from a question posted by someone else at the Mathematica StackexchangenikolaussucherFri, 08 Feb 2019 13:40:39 -0600http://ask.sagemath.org/question/45376/Minimal determinant of a matrix with varied entrieshttp://ask.sagemath.org/question/45367/minimal-determinant-of-a-matrix-with-varied-entries/I would like Sage to tell me to minimal value of the determinant of a matrix when a vary some entries over a set range.
For example, say with the 4x4 matrix A (sorry for weird layout, I can't get the Latex code to work properly?):
0 1 i j
1 0 1 k
0 1 0 1
0 0 1 0
I'd like to know, for $\{i,j,k} \in \{0, \pm1\}$, what the smallest non-trivial determinant is, and for which combination(s) of $i,j,k$ this is for.
I'm still pretty new to Sage, so I'm a bit unsure of how to do this effectively, if it is at all possible to do this?
Side note: I know I could of course write
sage A.determinant()
and this would give me the value of the determinant in terms of $i,j,k$. And in this example that would likely be much easier.
The idea is that I'd like to do this with larger matrices (that aren't as nice as this), more variables, etc. It would obviously be nicer to have have Sage simply compute the smallest determinant and give the corresponding values for the variables than me have to plug it in.LukeC93Fri, 08 Feb 2019 04:05:15 -0600http://ask.sagemath.org/question/45367/How do I save a rational matrix for Mathematica and Matlab to read?http://ask.sagemath.org/question/45141/how-do-i-save-a-rational-matrix-for-mathematica-and-matlab-to-read/Hi,
I create a rational matrix (rather large, say 1000x1000), and I want to save it in a file that can be read by Mathematica or MATLAB (with symbolic toolbox). Is there a simple way to do that?
Right now, I use
o = open('file.txt','w')
o.write(str(A))
o.close()
where A is the matrix. However, it has these "[" and "]" at the beginning of line that makes it difficult for Mathetmatica and MATLAB to read. Any suggestions would be appreciated.raykanTue, 22 Jan 2019 22:01:12 -0600http://ask.sagemath.org/question/45141/Speed a function with hex grid and primes numbershttp://ask.sagemath.org/question/44522/speed-a-function-with-hex-grid-and-primes-numbers/Hello, I am trying to solve the question 175 of the Turing Challenge. We create a network of hexagonal tiles containing the following integers 1, 2, 3, 4, ... I represent this network in a square matrix by placing the number 1 in the center of the matrix.
We must calculate the difference between each tile numbered n and each of its six neighbors, we will call DP (n) the number of these differences # which are a prime number.
My problem is this: I have to calculate a lot of times the function below. We save in DP3 the n which are surrounded by exactly 3 prime numbers.
Here is all my script. My idea is this: every time I have completed a turn I can calculate the DP3 of the previous turn. The program stops when len (DP3) = 2016. As the spirals become bigger and bigger you have to make more and more calls to the DP3 () search function.
My question is: **is it possible to speed up this function?**
PS: I'm sorry for my bad english. I also note that I am a beginner in programming.
# TURING 175 - Tuiles hexagonales (essai VII) DERNIER 26/11/18 OK ma!s trop lent
# Une tuile hexagonale portant le numéro 1 est entourée d'un anneau de six tuiles numérotées de 2 à 7, la première tuile de l'anneau étant # posée à midi et en tournant dans le sens inverse des aiguilles d'une montre.
# De nouveaux anneaux sont ajoutés de la même façon, les anneaux suivants étant numérotés 8 à 19, de 20 à 37, de 38 à 61, et ainsi de
# suite. Le diagramme ci-contre montre les trois premiers anneaux.
# En calculant la différence entre la tuile numérotée n et chacune de ses six voisines, nous appellerons DP(n) le nombre de ces différences # qui sont un nombre premier.
# Par exemple, autour de la tuile numéro 8, les différences sont 12, 29, 11, 6, 1 et 13. Donc DP(8)=3.
# De la même manière, autour de la tuile numéro 17, les différences sont 1, 17, 16, 1, 11 et 10, d'où DP(17)=2.
# On peut montrer que la valeur maximale de DP(n) est 3.
# Quand toutes les tuiles pour lesquelles DP(n)=3 sont énumérées dans l'ordre croissant pour former une suite, la 10ème tuile
# porte le numéro 271.
# Trouver le numéro de la 2016ème tuile de cette suite.
temps = walltime()
var('n,x,y')
def rechercheDP3(n,x,y):
n = M[x, y]
d = [ M[x-1, y], M[x, y+1], M[x+1, y+1], M[x+1, y], M[x, y-1], M[x-1, y-1] ] # les 6 cases qui entourent n
dp = len( [t for t in d if is_prime(abs(n-t))] )
if dp == 3:
DP3.append(n)
return
lim = 17 # Attention, il faut que lim soit impair
M = matrix(ZZ, lim, lim) # création matrice nulle M ATTENTION: X est vertical vers le bas & Y est horizontal vers la droite
x, y = lim//2, lim//2 # centre de M on compte à partir de 0
print "Centre:", x, y
M[x, y] = 1 # le nombre 1 est placé au centre puis le 1er tour (2,3,4,5,6,7)
M[x-1, y] = 2
M[x-1, y-1] = 3
M[x, y-1] = 4
M[x+1, y] = 5
M[x+1, y+1] = 6
M[x, y+1] = 7
n = 7
x_debut_prec, y_debut_prec = x-1, y
DP3 = [1]
maxtour = lim//2
tour = 1 # on a déjà placé le 1er tour 2...7
grandeur_deplact = 1 # plus la spirale est extérieure plus le déplacement est grand
print "maxtour = ", maxtour
print "*",walltime(temps)
#print M # valable si n est petit
#print
# on remplit la table en spirale
while tour < maxtour and len(DP3)<2016: # 2016 est la valeur demandée dans l'énoncé
tour += 1
grandeur_deplact +=1
# on se place au-dessus de la case de départ (2,8,20,...) -> 6 trajets de 1 au 1er tour, de 2 au 2d tour, de 3 au 3e tour, ....
x = x_debut_prec - 1
n += 1 #n = dernier_terme_tour + 1
M[x, y] = n
x_debut_suivant, y_debut_suivant = x, y # coord case départ tour suivant
for i in xrange(grandeur_deplact): # trajet 1 horizontal gauche
y = y-1
n += 1
M[x, y] = n
for i in xrange(grandeur_deplact): # trajet 2 vertical bas
x = x+1
n += 1
M[x, y] = n
for i in xrange(grandeur_deplact): # trajet 3 oblique bas droit
x = x+1
y = y+1
n += 1
M[x, y] = n
for i in xrange(grandeur_deplact): # trajet 4 horizontal droite
y = y+1
n += 1
M[x, y] = n
for i in xrange(grandeur_deplact): # trajet 5 vertical haut
x = x-1
n += 1
M[x, y] = n
for i in xrange(grandeur_deplact-1): # trajet 6 oblique haut gauche -1 car on retombe sur le 1er -> le tour est fini
x = x-1
y = y-1
n += 1
M[x, y] = n
dernier_tour_n = n # on mémorise le tour qu'on vient de faire
xfin_tour = x
yfin_tour = y
# recherche les dp3 -> on recommence le tour précédent et on cherche ses DP3
grandeur_deplact -= 1
# on se place au-début du tour précédent (2,8,20,38,62,92,...)
x,y = x_debut_prec, y_debut_prec
np = M[x,y] # np comme cela on ne touche pas à n
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact): # trajet 1 horizontal gauche
y = y-1
np += 1
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact): # trajet 2 vertical bas
x = x+1
np += 1
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact): # trajet 3 oblique bas droit
x = x+1
y = y+1
np += 1
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact): # trajet 4 horizontal droite
y = y+1
np += 1
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact): # trajet 5 vertical haut
x = x-1
np += 1
rechercheDP3(np,x,y)
for i in xrange(grandeur_deplact-1): # trajet 6 oblique haut gauche
x = x-1
y = y-1
np += 1
rechercheDP3(np,x,y)
# retour aux bonnes valeurs
grandeur_deplact += 1 # on revient à la valeur exacte pour le tour suivant
x = x_debut_suivant
y = y_debut_suivant
x_debut_prec, y_debut_prec = x_debut_suivant, y_debut_suivant
if len(DP3) >= 2016:
print DP3(2015)
else:
print "len(DP3) = ", len(DP3)
print "Durée = ", walltime(temps)wisherFri, 30 Nov 2018 10:31:22 -0600http://ask.sagemath.org/question/44522/Trying to get the right inverse, not possiblehttp://ask.sagemath.org/question/44503/trying-to-get-the-right-inverse-not-possible/ Hey guys,
I am working on a project and I am trying to find a matrix that is invertible using the following code:
e = 5;
n = 2;
m = 3;
s = 2;
t = 2;
b = 2;
mon = (b * n^s)^t
mon2 = b * n^s
#F_q is F_2/{irreducible element in F_2}
F.<r> = GF(2)[];
for p in F.polynomials(e):
if p.is_irreducible():
break;
K.<q> = GF(2^e, name='q', modulus=p);
Zn = Integers(2^(e*n)-1);
Zm = Integers(2^(e*m)-1);
R = PolynomialRing(K,'X');
R.inject_variables();
M1 = matrix(K,mon,mon);
M2 = matrix(K,mon,mon);
M1inv = matrix(K,mon,mon);
M2inv = matrix(K,mon,mon);
pt_sec2pub = matrix(K,mon,m*n);
#Constructing matrix A using the variables mentioned in the paper
A = matrix(Zn,m,m);
while True:
for i in range(0,m):
for j in range(0,m):
if(s<m):
if j==s-i:
A[i,j] = 0;
else:
A[i,j] = 2^(ZZ.random_element(0,n*e));
else:
A[i,j] = 2^(ZZ.random_element(0,n*e));
det = A.determinant();
if gcd(det,2^(e*n)-1) == 1:
break;
Ainv = matrix(Zn,m,m);
Ainv = A.inverse();
print A * Ainv
print Ainv * A
#Constructing matrix B using the variables mentioned in the paper
B = matrix(Zm,n,n);
while True:
for i in range(0,n):
for j in range(0,n):
if(t<n):
if j==t-i:
B[i,j] = 0;
else:
B[i,j] = 2^(ZZ.random_element(0,m*e));
else:
B[i,j] = 2^(ZZ.random_element(0,m*e));
det = B.determinant();
if gcd(det,2^(e*m)-1) == 1:
break;
Binv = matrix(Zm,m,m);
Binv = B.inverse();
print Binv * B
print B * Binv
# This computes the monomials generated when you apply G1 and G2 to the input. Instead of raising polynomials, you raise the elements of the polynomials to their respective element in A and B.
def compute_monomials_for_public_key(x):
row = matrix(K,t,mon2)
vector_result = matrix(K,mon*2,1)
# This is the vec1^(A[0][0]).lift() * vec2^(A[0][1]).lift() from G1
row[0,0] = x[0][0]^A[0][0].lift() * x[2][0] ^ A[0][1].lift()
row[0,1] = x[1][0]^A[0][0].lift() * x[2][0] ^ A[0][1].lift()
row[0,2] = x[0][0]^A[0][0].lift() * x[3][0] ^ A[0][1].lift()
row[0,3] = x[1][0]^A[0][0].lift() * x[3][0] ^ A[0][1].lift()
# This is the vec1^(A[1][0]).lift() * vec3^(A[1][2]).lift(); from G1
row[0,4] = x[0][0]^A[1][0].lift() * x[4][0] ^ A[1][2].lift()
row[0,5] = x[1][0]^A[1][0].lift() * x[4][0] ^ A[1][2].lift()
row[0,6] = x[0][0]^A[1][0].lift() * x[5][0] ^ A[1][2].lift()
row[0,7] = x[1][0]^A[1][0].lift() * x[5][0] ^ A[1][2].lift()
# This is the vec1^(A[1][0]).lift() * vec3^(A[1][2]).lift(); from G1
row[1,0] = x[0][0]^A[1][0].lift() * x[4][0] ^ A[1][2].lift()
row[1,1] = x[1][0]^A[1][0].lift() * x[4][0] ^ A[1][2].lift()
row[1,2] = x[0][0]^A[1][0].lift() * x[5][0] ^ A[1][2].lift()
row[1,3] = x[1][0]^A[1][0].lift() * x[5][0] ^ A[1][2].lift()
# This is the vec2^(A[2][1]).lift() * vec3^(A[2][2]).lift(); from G1
row[1,4] = x[2][0]^A[2][1].lift() * x[4][0] ^ A[2][2].lift()
row[1,5] = x[3][0]^A[2][1].lift() * x[4][0] ^ A[2][2].lift()
row[1,6] = x[2][0]^A[2][1].lift() * x[5][0] ^ A[2][2].lift()
row[1,7] = x[3][0]^A[2][1].lift() * x[5][0] ^ A[2][2].lift()
#print row
for i in range(0,mon2):
for j in range(0,mon2):
vector_result[mon2*i + j] = row[0][i] ^ B[0][0].lift() * row[1][j] ^ B[0][1].lift()
vector_result[mon2*i + j + mon] = row[0][i] ^ B[1][0].lift() * row[1][j] ^ B[1][1].lift()
return vector_result
def generateVectors():
while True:
for i in range(0,mon):
for j in range(0,m*n):
pt_sec2pub[i,j] = K.random_element();
transp = matrix(pt_sec2pub[i]).transpose();
#print "HA"
vec_transp = compute_monomials_for_public_key(transp);
for j in range(0,mon):
M1[j,i] = vec_transp[j][0];
M2[j,i] = vec_transp[j+mon][0];
#if i == 0:
#print vec_transp
print M1.is_invertible()
M1inv = M1.inverse()
print M1inv * M1
break;
generateVectors()
However, when e < 8, it always gives me that M1 is not invertible and I do not understand whether there is an issue in my logic or not. I am however able to compute the inverse of M1 but when I multiply it with M1, I expect the identity matrix, however this is not the case when e < 8. Please try with different values of e to see this happening. Please let me know if you manage to find anything.
ThanksLujminaThu, 29 Nov 2018 09:54:30 -0600http://ask.sagemath.org/question/44503/how to get the transformation matrix for a transformation over 4x4 matrices?http://ask.sagemath.org/question/44194/how-to-get-the-transformation-matrix-for-a-transformation-over-4x4-matrices/I have the following transformation:
M = MatrixSpace(QQ,4,4)
def f(m):
return matrix([
[m[0][0], m[0][1], m[0][2], m[0][3]],
[m[1][3], m[1][0], m[1][1], m[1][2]],
[m[2][2], m[2][3], m[2][0], m[2][1]],
[m[3][1], m[3][2], m[3][3], m[3][0]]
])
print linear_transformation(M, M, f)
This is not working - but I can't figure out what linear_transformation is expecting.
How can I get this to work? Is this even possible?rlswMon, 05 Nov 2018 14:00:31 -0600http://ask.sagemath.org/question/44194/Polynomial interpolation given a mathematic function f(x), an interval [a,b] and a natural number nhttp://ask.sagemath.org/question/43927/polynomial-interpolation-given-a-mathematic-function-fx-an-interval-ab-and-a-natural-number-n/Hi, i'm a computer science bachelor 's student and i'm having some trouble with this exercice, i'd like to get some help since it's my first course using sagemath, thanks, the exercice:
Write a function that takes as input a mathematical function f, an interval [a, b] and a natural n and return the interpolative polynomial of the function in the n + 1 points resulting from dividing the interval into subinterval n of equal length. That is to say, a polynomial p (x) of degree ≤ n such p (xi) = f (xi), where xi = a + i * ((b-a)/n) for all i = 0, ... n.
I'm stuck in the way of transforming a list into a matrix. This is what i've tried so far:
def list1(a,b,n):
r=(b-a)/n
return [a+i*r for i in range(n+1)]
def list2(a,b,n):
r=(b-a)/n
l=[]
for i in range(n+1):
l.append(a+i*r)
return l
def functionlist(f,llista):
return[f(i) for i in llista]
px=matrix(7, 1,list2(1, 5, 6))
show(px)
py=matrix(7, 1, functionlist(sin, list1(1, 5, 6)))
show(py)
points= zip(px,py); points
A=matrix(RDF,[[1,px[0],px[0]^2,px[0]^3],[1,px[1],px[1]^2,px[1]^3],[1,px[2],px[2]^2,px[2]^3],[1,px[3],px[3]^2,px[3]^3]]); A
And gives me this error:
NotImplementedError Traceback (most recent call last)
<ipython-input-112-a1670df9c827> in <module>()
19 points= zip(px,py); points
20
---> 21 A=matrix(RDF,[[Integer(1),px[Integer(0)],px[Integer(0)]**Integer(2),px[Integer(0)]**Integer(3)],[Integer(1),px[Integer(1)],px[Integer(1)]**Integer(2),px[Integer(1)]**Integer(3)],[Integer(1),px[Integer(2)],px[Integer(2)]**Integer(2),px[Integer(2)]**Integer(3)],[Integer(1),px[Integer(3)],px[Integer(3)]**Integer(2),px[Integer(3)]**Integer(3)]]); A
22
23
/opt/sagemath-8.3/local/lib/python2.7/site-packages/sage/modules/free_module_element.pyx in sage.modules.free_module_element.FreeModuleElement.__pow__ (build/cythonized/sage/modules/free_module_element.c:15842)()
2019 NotImplementedError
2020 """
-> 2021 raise NotImplementedError
2022
2023 def _repr_(self):
NotImplementedError:
Pls help, thanks.Hell_BoyFri, 12 Oct 2018 06:36:28 -0500http://ask.sagemath.org/question/43927/su2 matrix exponentiationhttp://ask.sagemath.org/question/43441/su2-matrix-exponentiation/Hi,
does anyone know if sage math is able to successfully calculate exp(G) where G belongs to su(2) ?
The sagemath commands are given below :
var('phi theta', domain='real')
u = vector([cos(phi)*sin(theta),sin(phi)*sin(theta),cos(theta)])
u.norm().simplify_trig()
sigma_x = matrix([[0,1],[1,0]])
sigma_y = matrix([[0,-i],[i,0]])
sigma_z = matrix([[1,0],[0,-1]])
sigma_x, sigma_y, sigma_z
var('t',domain='real')
G = -i*t*(sigma_x*u[0]+sigma_y*u[1]+sigma_z*u[2])
G.trace(), (G.det()/t**2).simplify_full(), G.is_hermitian()
exp(G)
exp(G) returns the following error code :
> TypeError: ECL says: Error executing
> code in Maxima: Unable to find the
> spectral representation
Thank you for helping.
EpiepimetheusWed, 22 Aug 2018 06:57:53 -0500http://ask.sagemath.org/question/43441/Quaternions Missing Important Functionality?http://ask.sagemath.org/question/34587/quaternions-missing-important-functionality/I use quaternions and Clifford algebras frequently for solving PDE boundary value problems as well as things like reflections, rotations etc. The underlying field for my quaternions is almost always either the complex numbers or the symbolic ring.
I am making an attempt to use them in Sage but I've run into a couple of obstacles that have given me pause. The absolute first things I looked for were,
1) scalar part or real part of the quaternion. Where is this function? I stumbled upon turning it into a list or vector but I presume that just taking the scalar part would be more efficient than dumping all the coefficients. For matrix representations it's often just the trace of the matrix. Correspondingly obtaining the vector part should be a standard function as well.
2) Quaternion automorphisms and anti-automorphisms? where are they? Yes we have conjugate which is both a method and an external function but what about the reversion and involution and the many other automorphisms? I don't expect to have to multiply by a bunch of unit vectors to get them for efficiency reasons. Also how do I distinguish between the quaternion conjugate and the complex conjugate of each of it's elements? This is a very important distinction that I would not know how to do without stripping out it's components and then remapping it.
3) Constructing a quaternion from coefficients. The only examples I've seen require explicit multiplications like
q = q0 + q1 * i + q2 * j + q3 * k . That doesn't seem efficient.
4) quaternions as elements of enclosing matrices and vectors. This would be very helpful since you could generate any Clifford algebra with this and it's often easier to analyze the components of said algebra that are isomorphic to Quaternions or Biquaternions in the complex case. Moreover I need to be able to do this for quaternions over the symbolic ring. It fails for me as this example from sage 7.3 shows:
<pre><code>
Q.<e1,e2,e3> = QuaternionAlgebra(SR, -1,-1)
var('x y z', domain='real')
q1 = x + x * I * e1
q2 = x - x * I * e1
v = vector([q1,q2])
</code></pre>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_36.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("US48ZTEsZTIsZTM+ID0gUXVhdGVybmlvbkFsZ2VicmEoU1IsIC0xLC0xKQp2YXIoJ3ggeSB6JywgZG9tYWluPSdyZWFsJykKcTEgPSB4ICsgeCAqIEkgKiBlMQpxMiA9IHggLSB4ICogSSAqIGUxCnYgPSB2ZWN0b3IoW3ExLHEyXSk="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/tmp/tmpQ0ibdW/___code___.py", line 7, in <module>
exec compile(u'v = vector([q1,q2]) File "", line 1, in <module>
File "sage/modules/free_module_element.pyx", line 510, in sage.modules.free_module_element.vector (/data/AppData/SageMath/src/build/cythonized/sage/modules/free_module_element.c:5811)
TypeError: unsupported operand type(s) for ** or pow(): 'QuaternionAlgebra_ab' and 'int'
5) quaternion rotations. Most libraries will generate the unit quaternion that rotates in 3D space and/or have a function that applies it efficiently.
There are probably a few other things like generating a canonical matrix representation for a full quaternion and so forth. I actually wonder if the default quaternion package is the right tool for a physicist or an engineer or someone who wants to play around with the so called geometric algebra of Hestenes. It seems the perogatives of the scientist vs the algebraist are very very different. How efficient is this library? What if I had to multiply millions of quaternions? I'm guessing I'd be better off mapping it to complex matrices and invoking blas.
While most of the functionality can be added on via a little python programming, I am concerned about efficiency and consistency. Moreover item 4 is a bit of a quandary since it involves overloading a bunch of arithmetic operators and some new python classes and so forth.
I'm hoping someone will tell me that it's all there, I just wasn't able to find it in the documentation or so forth. Thanks for any help in advance.doomThu, 25 Aug 2016 21:11:21 -0500http://ask.sagemath.org/question/34587/Optimizing a function of a given matrixhttp://ask.sagemath.org/question/43124/optimizing-a-function-of-a-given-matrix/ Let us consider the $4\times 4$ symmetric matrix $$ A_x=\left(\begin{array}{rrrr}
0 & 1 & 1 & 1 \\
1 & 0 & 2^x & 2^x \\
1 & 2^x & 0 & 2^x \\
1 & 2^x & 2^x & 0
\end{array}\right) $$
Here I need to find $\min \{ x>0: det(A_x)=0 \, or \, ||A_x^{-1}||=0 \} ,$ where by $||M||$ we mean the sum of all entries of the matrix $M.$ I'm looking for a general sage program where my input will be a matrix with entries as functions of an inderminant (like the matrix $A_x$ above) which will give me the unique $x$ corresponding to my matrix. If no such real value exists, it should result as $\infty$ Can anyone help me? Thank you in advance.Deepak SarmaMon, 23 Jul 2018 09:50:52 -0500http://ask.sagemath.org/question/43124/How to create a matrix in sage that expands with a variable number of rows and columns and in each row the values are squared?http://ask.sagemath.org/question/39986/how-to-create-a-matrix-in-sage-that-expands-with-a-variable-number-of-rows-and-columns-and-in-each-row-the-values-are-squared/I need to make a code that takes takes two inputs: n and d and creates a matrix of the values of a list P.
'n' will be the number of columns and 'd' the number of rows.
In each row, I need the values of the following row to be raised to an incrementally rising power.
This is what I have so far:
# inputs
n = 5
d = 5
f = x^2
# list of size n
P = [(i, f(i)) for i in range(n)]
# matrix
C = matrix([(P[i][0]) for i in range(n)])
show(C)sageAmateur345Wed, 06 Dec 2017 20:28:33 -0600http://ask.sagemath.org/question/39986/How to force a matrix display accordingly?http://ask.sagemath.org/question/42874/how-to-force-a-matrix-display-accordingly/I am working with matrix groups in small and large dimensions (>20 or >100). Is there a way to fleece sage to make a matrix display as “ d x d matrix over <Ring>” where d>20? It does not do this for any matrix groups like Coxeter/Affine/Weyl/Braid TL Rep. etc.
CoxeterGroup([‘A20’]).gens()[0]
“21 x 21 matrix over Integer Ring”ChernoxylMon, 09 Jul 2018 17:55:28 -0500http://ask.sagemath.org/question/42874/How do I normalize the columns of a matrix?http://ask.sagemath.org/question/42579/how-do-i-normalize-the-columns-of-a-matrix/ How do I normalize the columns of a matrix?
such as $A = matrix(5,5,[\text{some numbers}])$ionsmeTue, 12 Jun 2018 17:39:51 -0500http://ask.sagemath.org/question/42579/Matrix Group over Symbolic Ringhttp://ask.sagemath.org/question/40976/matrix-group-over-symbolic-ring/I have problem on generate matrix group over symbolic ring.
First, I define
eta=I;
eta2=(1+I)*sqrt(2)/2;
Then, define a generator matrix
T=matrix(SR,4,[eta**(i*j)*eta2/2 for i in range(4) for j in range(4)]);
I try to make a matrix group by
G=MatrixGroup(T);
What I get is only very long computation that does not give any result.
Can somebody help me? Thank you very much.
I have checked the order of T, I got 8 since T**8=I where I is identity matrix. dimahphoneSun, 04 Feb 2018 22:31:14 -0600http://ask.sagemath.org/question/40976/How to solve a large list of simultaneous equationshttp://ask.sagemath.org/question/42172/how-to-solve-a-large-list-of-simultaneous-equations/I am trying to solve a particular problem, but my test solution for setting up the code isn't working. I have tried two ways - one, which just outputs the same equations, and the other, I'm unsure on how to solve this large list of equations which are unrealistic to type out.
First attempt
var('a b c d e f g h i')
X=matrix(3,3,[[0,1,0],[0,0,1],[1,0,0]])
P=matrix(3,3,[[a,b,c],[d,e,f],[g,h,i]])
Pdagger=P.transpose()
Xdagger=X.transpose()
L=P*X*Pdagger
This outputs $$\begin{pmatrix} ab+ac+bc & cd+ae+bf & cg+ah+bi \\\\ bd+ce+af & de+df+ef & fg+dh+ei \\\\ bg+ch+ai & eg+fh+di & gh+gi+hi \end{pmatrix}$$ I then make $L=X$, then type these equations element wise into the simultaneous equation solver;
equations=solve([a*b+a*c+b*c==0,c*d+a*e+b*f==1,c*g+a*h+b*i==0,b*d+c*e+a*f==0,d*e+d*f+e*f==0,f*g+d*h+e*i==1,b*g+c*h+a*i==1,e*g+f*h+d*i==0,g*h+g*i+h*i==0],a,b,c,d,e,f,g,h,i)
The output:
a*e + b*f == 1, d*e + d*f + e*f == 0, b*g + c*h + a*i == 1, c*g + a*h + b*i == 0, e*g + f*h + d*i == 0, f*g + d*h + e*i == 1, g*h + g*i + h*i == 0]
Second attempt;
Q=X*Pdagger
B=Q.solve_left(X)
eqn=[]
for i in range(0,3):
for j in range(0,3):
eqn.append(B[i][j])
This gives me a list of the equations, I then try the solver again;
solve([eqn[0]==0,...eqn[8]==0],a,b,c,d,e,f,g,h,i)
This just gives me an error:
(a, b, c, d, e, f, g, h, i)
Error in lines 13-13
Traceback (most recent call last):
File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1013, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in <module>
File "/ext/sage/sage-8.1/local/lib/python2.7/site-packages/sage/symbolic/relation.py", line 976, in solve
raise TypeError("%s is not a valid variable." % repr(i))
TypeError: 2 is not a valid variable.
The hope is that I will be able to extend this to larger matrices, so autonomy is welcomed greatly. But I will happily take any advice given I'm at a completely lose end. It is worth noting that the solution to this problem; $$PXP^{\dagger}=X$ is the identity matrix. My understanding is that the first method cannot find a closed form? I have even tried specifying that a,b,c,d,e,f,g,h,i are all 0 or 1 and this has not helped. I believe my second method is more on the right track, however I cannot afford to manually type out the 9 non-linear equations that pop out from the matrix solver.PatrickLewisWed, 25 Apr 2018 17:53:15 -0500http://ask.sagemath.org/question/42172/How does list_plot3d interpret nxn matrices?http://ask.sagemath.org/question/42091/how-does-list_plot3d-interpret-nxn-matrices/ From the [documentation](http://doc.sagemath.org/html/en/reference/plot3d/sage/plot/plot3d/list_plot3d.html) of `list_plot3d`
>INPUT:
>v - something that defines a set of points in 3 space, for example:
> - a matrix
> - a list of 3-tuples
> - a list of lists (all of the same length) - this is treated the same as a matrix.
Intuitively I would guess that the function would only accept $3 \times n$ matrices and/or their transposes, but the first example on the document page is a plot of a five by five matrix
n = 5
m = matrix(RDF, n, [(i+j)%n for i in [1..n] for j in [1..n]])
p = list_plot3d(m)
p
**Question**: How does `list_plot3d` interpret this $5 \times 5$ matrix as a set of points in 3-space?
One might suspect that `list_plot3d` handles matrices the same was as, for example, `point3d` but this is not the case. For example, the points visualized by `point3d` do not lie on the surface given by `list_plot3d` in the above example as witnessed by
p + point3d(m, size=33)
amdallWed, 18 Apr 2018 13:34:16 -0500http://ask.sagemath.org/question/42091/(how/can) i declair this isomorphismhttp://ask.sagemath.org/question/41593/howcan-i-declair-this-isomorphism/Hi,
let $U$ be a square matrix of order $m$ over $\mathbb F_{q}$, more precisely $U$ is the companion matrix of a monic irreducible polynomial over $\mathbb F_{q}$ that define $\mathbb F_{q^m}$ .
let $\alpha$ be a primitive element of $\mathbb F_{q^m}$
I wish to declare this morphism to compute some examples with SAGEMATH
$\psi$: $\mathbb F_{q^m}$ $\rightarrow$ $\mathbb{F}_{q}[U]$
$\alpha$ $\mapsto$ $\psi(\alpha)=U$
thanks in advance;TWJFri, 16 Mar 2018 18:53:34 -0500http://ask.sagemath.org/question/41593/solving matrix over GF(2)http://ask.sagemath.org/question/41575/solving-matrix-over-gf2/ A = matrix(GF(2), 8, 8, [])
b = vector(GF(2), [0, 1, 1, 0, 1, 0, 1, 1])
y = vector(GF(2), [0, 0, 0, 0, 1, 0, 1, 1])
x = vector(GF(2), [1, 0, 0, 0, 0, 0, 0, 0])
If the matrix $A$ is unkown, we have $Ax+b = y$.
How can we solve the matrix $A$?
omggggggThu, 15 Mar 2018 20:06:28 -0500http://ask.sagemath.org/question/41575/iteration of a matrixhttp://ask.sagemath.org/question/41064/iteration-of-a-matrix/ Hello community,
I have the following question. I have a matrix defined as K. And its diagonal defined, for instance, as `z = [1, 2, 3, 4, 5]`. I need to change each entry of a diagonal one by one, and then check a condition using 'if' statement. For example, change z to `[2, 2, 3, 4, 5] ` and then `[1, 3, 3, 4, 5]` and then `[1, 2, 4, 4, 5]` (increasing each element by 1)
Now I have a code :
for i in range(16):
K1 = K
K1[i,i] = K[i,i] + 1
V1 = p1 * K1 * p1t
V2 = p2 * K1 * p2t
if V2 < V1:
print i
So the first three rows are more interesting for the problem. The problem is, this code changes each entry, not returning the previous one to the initial position. So it changes the diagonal as following: `[1, 2, 3, 4, 5]` to `[2, 2, 3, 4, 5]` to `[2, 3, 3, 4, 5]` to `[2, 3, 4, 4, 5]` etc. How can I modify this code to correct the problem? Thank you.XeniaSun, 11 Feb 2018 11:56:11 -0600http://ask.sagemath.org/question/41064/Making a dictionary of matrices, and save the sessionhttp://ask.sagemath.org/question/40756/making-a-dictionary-of-matrices-and-save-the-session/Some time ago I [made a dictionary of matrices](https://ask.sagemath.org/question/40234/) with your help.
Now I like to save the session by `save_session()` but somehow I fail. The terminal goes as follows
sage: A=matrix(GF(2),[[1,0],[0,1]])
sage: A.set_immutable()
sage: dictA={A:1}
sage: save_session(verbose=true)
Saving A
Not saving dictA: mutable matrices are unhashable
On the other hand
sage: A=matrix([[1,0],[0,1]])
sage: A.set_immutable()
sage: dictA={A:1}
sage: save_session(verbose=true)
Saving A
Saving dictA
I have no idea why specifying `GF(2)` fails `save_session()`. Does anyone know a fix?Symbol 1Tue, 23 Jan 2018 18:32:17 -0600http://ask.sagemath.org/question/40756/Copying a Matrixhttp://ask.sagemath.org/question/40754/copying-a-matrix/I'm trying to take the Singular Value Decomposition of the adjacency matrix of a graph A, but all my "reasonable" attempts at doing so have failed, see the code below.
I believe the problem has something to do with the matrix being immutable, so I've been trying to copy A into a different matrix M and then perform SVD on M. he only thing that I've found to work is to essentially build A from scratch, but there must be a better method.
sage: A=graphs.CycleGraph(3).adjacency_matrix()
#Method 1: Try and get SVD directly from A; gives error at last step.
#sage: A.change_ring(RDF)
#sage: A.SVD()
#Method 2: Try and copy A to a different matrix and then do SVD; gives error at last step.
# sage: M=copy(A)
# sage: M.change_ring(RDF)
# sage: M.SVD()
#Method 3: Build A up again from scratch and then do SVD; works, but is tedious.
sage: M=matrix(RDF,3,3)
sage: for i in [0..2]:
for j in [0..2]:
if(A[i,j]==1):
M[i,j]=1
sage: M.SVD()zorkkoiTue, 23 Jan 2018 12:44:19 -0600http://ask.sagemath.org/question/40754/Complimentary eigenvalue of a matrixhttp://ask.sagemath.org/question/40540/complimentary-eigenvalue-of-a-matrix/How to obtain all the complimentary eigenvalues (also associated complimentary eigenvectors) of a given matrix. Complimentary eigenvalues and eigenvectors of a given matrix $A$ of order $n\times n$ is the solution to the following system
$x≥0_n$,
$Ax−λx≥0_n$ and
$⟨x, Ax−λx⟩=0$ where $x(\neq 0_n)\in R^n$Deepak SarmaTue, 09 Jan 2018 01:03:31 -0600http://ask.sagemath.org/question/40540/Limit of a matrix powerhttp://ask.sagemath.org/question/40248/limit-of-a-matrix-power/Hello!
I'm new in Sagemath and I want to calculate the limit of the power of a given 3x3 diagonal matrix:
J=matrix([[1,0,0],[0,-1/2-1/2*I,0],[0,0,-1/2+1/2*I]]); #Given diagonal matrix
n=var('n');
limit(J^n,n=infinity) #The limit command fails =(
Is there any way to do this?
Trank you so much!dg.aragonesWed, 20 Dec 2017 02:17:31 -0600http://ask.sagemath.org/question/40248/Making a dictionary of matriceshttp://ask.sagemath.org/question/40234/making-a-dictionary-of-matrices/I am trying to make a dictionary of matrices. Ideally
MatDic={
matrix(GF(2),2,[1,0,0,1]):'a',
matrix(GF(2),2,[1,1,0,1]):'b'
# etc
}
But Sage refuses to hash (mutable) matrices. I then tried
MatDic={
matrix(GF(2),2,[1,0,0,1]).set_immutable():'a',
matrix(GF(2),2,[1,1,0,1]).set_immutable():'b'
}
MatDic
which gives
{None: 'b'}
I also tried making a dictionary of tuples
MatDic={
(1,0,0,1):'a',
(1,1,0,1):'b'
}
which raises no errors; However
MatDic[tuple(matrix(GF(2),2,[1,0,0,1]))]
gives
> TypeError: mutable vectors are unhashable
What is the best, if possible, way to make a dictionary and lookup matrices?Symbol 1Tue, 19 Dec 2017 12:24:10 -0600http://ask.sagemath.org/question/40234/Matrix Permutationshttp://ask.sagemath.org/question/40180/matrix-permutations/ Hello,
how do I get all permutations of a Matrix?
For the following exercise I would like to get all permutations of a Matrix with integer values in the range $0$ to $9$. There should be $10^4$ permutations. And then generate the permutations of tuples with three matrices. $10^{12}$ permutations and then I would filter the list somehow for the invertible matrices.
Is there a better way?
Exercise:
Let $S, T, U \in \mathbb{R}^{2x2}$ such that, $S_{i, j}, T_{i, j}, U_{i, j} \in \{0,1, \cdots, 9\}$
How many of the products $S \cdot T \cdot U$ are invertible?
In the Sage reference for permutation I couldn't find any thing.
Thanks
PS: The curly braces couldn't be escaped properly in the LaTex part ... \\{0,1, \cdots, 9\\}AsgFri, 15 Dec 2017 11:34:07 -0600http://ask.sagemath.org/question/40180/matrix with fractional numberhttp://ask.sagemath.org/question/39828/matrix-with-fractional-number/**m = matrix(ZZ, 3, 3, lambda i, j: 1/(i + j) ); m**
Sage tells me the following:
**Traceback (click to the left of this block for traceback)**
...
**ZeroDivisionError: rational division by zero**
why? it really confused me.lijianingTue, 28 Nov 2017 08:32:59 -0600http://ask.sagemath.org/question/39828/Characteristic polynomial wont be used in solvehttp://ask.sagemath.org/question/39746/characteristic-polynomial-wont-be-used-in-solve/ When I try to find roots in a characteristic polynomial it gives me errors:
sage: #Diagonalmatrix
....:
....:
....: A=matrix([[1,-1,2],
....: [-1,1,2],
....: [2,2,-2]])
....: var('x')
....: poly=A.characteristic_polynomial()
....: eq1=solve(poly==0,x)
....:
x
--------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-86-fee7a7de2ea1> in <module>()
7 var('x')
8 poly=A.characteristic_polynomial()
----> 9 eq1=solve(poly==Integer(0),x)
/usr/lib/python2.7/site-packages/sage/symbolic/relation.pyc in solve(f, *args, **kwds)
816
817 if not isinstance(f, (list, tuple)):
--> 818 raise TypeError("The first argument must be a symbolic expression or a list of symbolic expressions.")
819
820 if len(f)==1:
TypeError: The first argument must be a symbolic expression or a list of symbolic expressions.
sage:
What can I do in order to use the polynomial in an equation I wish to solve?PoetastropheThu, 23 Nov 2017 11:18:11 -0600http://ask.sagemath.org/question/39746/Variable matriceshttp://ask.sagemath.org/question/39687/variable-matrices/ If I type M = matrix(SR, 2, var('a,b,c,d')); show(~M), it gives me the inverse of the matrix M with entries in terms of a,b,c,d. Now what I want is to set four variable matrices A,B,C,D each of size 2x2 and then I want to create the block matrix N=block_matrix([[A, B], [C, D]]). Finally I want some functions of N in terms of A,B,C,D (say det(N)).Deepak SarmaMon, 20 Nov 2017 23:01:49 -0600http://ask.sagemath.org/question/39687/summation of matriceshttp://ask.sagemath.org/question/39638/summation-of-matrices/ Can we use sum function to add a number of matrices? If not, then how to add a number of matrices with just a single command. Suppose I want to create 10 random matrices of order 5x5 and then want their sum as a result. I tried the following command, but it didn't work.
A_{i}=random_matrix(ZZ,5,5) for i in range(1,10);
sum(A_{i}, i, 1, 10)
Note: I even could not generate 10 random matrices with the above command.
Deepak SarmaFri, 17 Nov 2017 05:15:03 -0600http://ask.sagemath.org/question/39638/command to get eigenvalueshttp://ask.sagemath.org/question/39621/command-to-get-eigenvalues/ If a matrix is given for heigher order ..i want to know how to get eigen values by sage.RajniThu, 16 Nov 2017 22:23:02 -0600http://ask.sagemath.org/question/39621/