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.Tue, 16 Apr 2019 13:20:09 -0500General solution for a matrixhttp://ask.sagemath.org/question/46229/general-solution-for-a-matrix/I have a matrix named `p` and with the values
[-10*x1 - 4*x2 + 14, -4*x1 - 2*x2 + 6]
When I try to solve the matrix with this line:
print(p(p.arguments()[0] == 0, p.arguments()[1] == 0))
I get this error:
ValueError: use named arguments, like EXPR(x=..., y=...)
In general i want to use something like this, the arguments are x1 and x2 and the x is a list of numbers that it will change on every loop
print(p([i == j for i,j in zip(f.arguments(), x)]))
But it reproduce the same errorscrNameTue, 16 Apr 2019 13:20:09 -0500http://ask.sagemath.org/question/46229/Variable matriceshttp://ask.sagemath.org/question/39687/variable-matrices/If I type
sage: M = matrix(SR, 2, var('a,b,c,d'))
sage: 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
sage: N = block_matrix([[A, B], [C, D]])
Finally I want some functions of `N` in terms of `A`, `B`, `C`, `D`.
For example, how can I get `det(N)` in terms of `A`, `B`, `C`, `D`?Deepak SarmaMon, 20 Nov 2017 23:01:49 -0600http://ask.sagemath.org/question/39687/Unflatten a vectorhttp://ask.sagemath.org/question/46062/unflatten-a-vector/I have a vector say a $9 \times 1$ vector which looks like
$$\begin{bmatrix}
2x +1 \newline
x \newline
1 \newline
x \newline
x^2 + 2x \newline
2x \newline
x \newline
2x^2 \newline
0 \newline
\end{bmatrix}$$
with entries in $\mathbb{F}_3[x]$.
There are 9 rows in this matrix and i want to write a function which
takes an $n^2 \times 1$ matrix and turns it into a $n \times n$ matrix.
So, in this case, we want the function would turn the above vector into
$$
\begin{bmatrix}
2x+1 & x & 1 \newline
x & x^2+2x & 2x \newline
x & 2x^2 & 0 \newline
\end{bmatrix}
$$
In this Sage, I tried this:
sage: v = Matrix(GF(3)[x], [[2*x+1],[x],[1],[x],[x^2+2*x],[2*x],[x],[2*x^2],[0]])
Then, write the following:
sage: Matrix(v.base_ring(), 3, 3, v)
This gave an error:
inconsistent number of rows: should be 3 but got 1abelTue, 09 Apr 2019 08:22:18 -0500http://ask.sagemath.org/question/46062/Can I use the "sr.lin_matrix ()" command for any S-Box?http://ask.sagemath.org/question/46002/can-i-use-the-srlin_matrix-command-for-any-s-box/ sage: sr = mq.SR(1, 1, 1, 8, gf2=True)
sage: S = sr.sbox(); S
(99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22)
sage: sr.lin_matrix()
[1 1 1 1 1 0 0 0]
[0 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 0]
[0 0 0 1 1 1 1 1]
[1 0 0 0 1 1 1 1]
[1 1 0 0 0 1 1 1]
[1 1 1 0 0 0 1 1]
[1 1 1 1 0 0 0 1]MarcioWed, 03 Apr 2019 08:18:58 -0500http://ask.sagemath.org/question/46002/How do I get the result of right_kernel into a matrix?http://ask.sagemath.org/question/45935/how-do-i-get-the-result-of-right_kernel-into-a-matrix/Hello,
I have a simple program I am running where I define a matrix C, then define
B=C.right_kernel()
I would then like to create another matrix, D, that is a block matrix with C and B as blocks, C on top of B. So far my code for that is
Dlist = []
for i in range(len(rowsofmatrix)):
Dlist.append(C[i,:])
for i in range(20-len(rowsofmatrix)):
Dlist.append(B[i,:])
where rowsofmatrix is a list I used to define the matrix C. The Dlist.append(C[I,:]) works just fine, but the second one involving B does not, and I imagine this has something to do with the form of B. Is there a way I can express B as a regular matrix? Or, alternatively, is there a better way to do this altogether?
ThankscaucherThu, 28 Mar 2019 20:00:40 -0500http://ask.sagemath.org/question/45935/Solve symbolic matrix cellhttp://ask.sagemath.org/question/45841/solve-symbolic-matrix-cell/I'm trying to take a cell from a matrix and solve for a variable symbolically. When I run this, I get the error:
TypeError: The first argument must be a symbolic expression or a list of symbolic expressions.
This is the code I am trying to execute:
var('a','b','c','x','y','z')
Rz = matrix([[cos(a),-sin(a),0,0],[sin(a),cos(a),0,0],[0,0,1,0],[0,0,0,1]])
Ry = matrix([[cos(b),0,sin(b),0],[0,1,0,0],[-sin(b),0,cos(b),0],[0,0,0,1]])
Rx = matrix([[1,0,0,0],[0,cos(c),-sin(c),0],[0,sin(c),cos(c),0],[0,0,0,1]])
P = matrix([[x],[y],[z],[1]])
Rzyxp = Rz * Ry * Rx * P
show(Rzyxp)
eqn2 = Rzyxp[2]
show(eqn2)
result1 = solve(eqn2==0, b)
show(result1)
Any help would be appreciatedMickey_PhippsTue, 19 Mar 2019 14:44:52 -0500http://ask.sagemath.org/question/45841/Generate a random non-singular matrix?http://ask.sagemath.org/question/45579/generate-a-random-non-singular-matrix/I do this in a loop now:
while:
A = random_matrix(...)
if(not A.is_singular()):
....
But this is innefficient. How do I generate random matrices with more concrete properties in sage?rijndaelxyzThu, 28 Feb 2019 23:44:45 -0600http://ask.sagemath.org/question/45579/Count number of ones in a set of matrixhttp://ask.sagemath.org/question/45540/count-number-of-ones-in-a-set-of-matrix/I am having the following code:
v = MatrixSpace(GF(2),2,2)
c = [0]*2
for vv in v.list():
t=sum(vv)
c = [x+y for x,y in zip(c,t)]
print c
My goal is to count how many '1s' that I have for each column within the set of matrices. For example with the first 4 matrices in the set:
[0 0] [1 0] [0 1] [0 0]
[0 0], [0 0], [0 0], [1 0]
I expect to receive [2,1] as a result, i.e. there are 2 of '1s' appear in the 1st column and 1 of '1s' appears in the 2nd column. However, I got [0, 1], because it's binary base.
Thank you for reading my problem and support :)imnvshSun, 24 Feb 2019 20:15:10 -0600http://ask.sagemath.org/question/45540/Given a value and conditions, find a matrix with that value as its determinanthttp://ask.sagemath.org/question/45527/given-a-value-and-conditions-find-a-matrix-with-that-value-as-its-determinant/ I'm not sure if the title is named too obscurely, so I'll give an example of what I'm talking.
Say we have an integer matrix:
M= 0 a
b 0 (sorry for weird formatting; cannot seem to write matrices properly on here - any help with that as well? :P )
I want to find all values $(a,b) \in (-2,-1,0,1,2)$ such that $det(M)=2$.
I've tried the following but I'm not sure how to finish it off / if this is the right way to go:
import itertools
for (a,b) in itertools.product([-2,-1,0,1,2], repeat=2):
M = Matrix(ZZ, [[0,a],[b,0]])
if M.determinant()==2:
min_params.append((a,b))
elif
min_params = [(a,b)]
print 'Sets of parameters with this determinant:', min_params
As I say, I feel like the start would be a good way to go, but I'm stuck when reaching `elif`, and I'm not sure if this is the right way to tackle this anyway!
Any help would be great!LukeC93Thu, 21 Feb 2019 06:01:41 -0600http://ask.sagemath.org/question/45527/Is 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/