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.Mon, 03 Feb 2020 07:27:19 -0600Generate >2D Matrixhttp://ask.sagemath.org/question/49762/generate-2d-matrix/I am trying to find a concise way to store data in a single variable for easy computational referencing. This data is basically an n-length vector of 2x2 matrices. I would like to be able to do linear algebra on the 2x2 matrices, but each of the n elements are handled separately. Is there an easy way to do this?
Basically, this would be the equivalent of a nx2x2 array in Numpy. The reason I want to use Sage instead of Numpy, is because there is a lot of linear algebra, including some symbolic, that needs to be performed. Numpy and Sympy are too slow for this. I've been able to do these computations in Maxima with an acceptable speed. For ease of interfacing with my Python script, I would like to just use Sage. This would also make things much easier if I do still need to push some of the computation to Maxima.mattbMon, 03 Feb 2020 07:27:19 -0600http://ask.sagemath.org/question/49762/matrix base ring changes by a complex multiplicationhttp://ask.sagemath.org/question/49557/matrix-base-ring-changes-by-a-complex-multiplication/The complex multiplication of matrix changes the base ring.
A = matrix(CDF,[[1,2],[3,4]]); print(A)
B = 2*A
C = I*A
print(type(A))
print(type(B))
print(type(C))
The result is
[1.0 2.0]
[3.0 4.0]
<class 'sage.matrix.matrix_complex_double_dense.Matrix_complex_double_dense'>
<class 'sage.matrix.matrix_complex_double_dense.Matrix_complex_double_dense'>
<class 'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'>
So the multiplication by an imaginary number breaks the CDF property.
This is very inconvenient for numerical calculations, because the symbolic computation is very slow.cxrjddWed, 15 Jan 2020 03:59:29 -0600http://ask.sagemath.org/question/49557/Exponential function does not work for diagonal matriceshttp://ask.sagemath.org/question/49190/exponential-function-does-not-work-for-diagonal-matrices/ D = diagonal_matrix([0])
exp(D)dejongWed, 25 Dec 2019 14:27:47 -0600http://ask.sagemath.org/question/49190/Add commas after matrix-elements in matrix()http://ask.sagemath.org/question/49184/add-commas-after-matrix-elements-in-matrix/I want to replace the brackets, but to add commas after each matrix-element, except the last ones in the rows.
I get only the first part.
Is there an elementary way to add commas to the sage-matrix? <br>
*Because `matrix()` has the great advantage that the elements are **aligned** in all cases.*
m = matrix([[2222,333,44444], [1,0,0]])
mymatrix = m.str().replace('[', '').replace(']', '') # replace [, ]
#.... # add commas
print mymatrix
Out Actual:
2222 333 44444
1 0 0
Out Target:
2222, 333, 44444
1, 0, 0geroyxWed, 25 Dec 2019 13:06:27 -0600http://ask.sagemath.org/question/49184/Keeping zeros after matrix multiplicationhttp://ask.sagemath.org/question/48925/keeping-zeros-after-matrix-multiplication/ Hello, Sage Community!
Suppose I do the following:
var('x y z')
u = vector([0, 1, 1])
v = vector([x, y, z])
u * v
The result is obviously `y+z`. I would like to keep the zeros after the multiplication, in order to have `0x+y+z` as my result. Is it possible?
Thanks in advance for your answers!dsejasSun, 01 Dec 2019 10:46:45 -0600http://ask.sagemath.org/question/48925/Absence of column vectorshttp://ask.sagemath.org/question/48860/absence-of-column-vectors/ I'm curious as to why column vecotrs seem to be non-existent in sage. To give you some context, I work with the following system:
R3 = IntegerModRing(3)
c_7_4 = [
[1, 0, -2, 0, 0, 0, 1],
[1, 1, 0, 0, -2, 0, 0],
[0, 1, 1, 0, 0, -2, 0],
[0, 0, 1, 1, 0, 0, -2],
[0, -2, 0, 1, 1, 0, 0],
[-2, 0, 0, 0, 1, 1, 0],
[0, 0, 0, -2, 0, 1, 1]
]
C3 = Matrix(R3, c_7_4)
B3 = C3.right_kernel().basis()
Clearly, the right kernel of C3 is a column vector, but if you run this code, you would find that
print(B3[0]) # returns a row vector
print(B3[0] * C3) # returns an answer
print(C3 * B3[0]) # returns an answer
Given that a column matrix should reasonably be written
[[a],[b]]
Why is this not the case? Specifically, is there a coding limitation to what the programmers can do which forces them to implement it in this way, or is there some mathematical usefulness to this which is beyond my understanding?
Thanks!
KraigSat, 23 Nov 2019 11:44:38 -0600http://ask.sagemath.org/question/48860/[Sage vs Python] Matrix indexing and list standardshttp://ask.sagemath.org/question/48802/sage-vs-python-matrix-indexing-and-list-standards/Hello, Sage Community!
Since I learned Sage, I have used the notation `A[i][j]` (which obviously came from my previous experience with Python lists) to access the (i+1, j+1)-th element of a matrix. However, I discovered a few weeks ago that I can also use the syntax `A[i,j]`. I am wondering which of these two ways of matrix indexing is preferred in Sage?
My tests using `timeit` indicate that the second syntax is faster than the first one by a factor of 500. So I suppose it to be simply natural that the fastest syntax is preferred. However, why to deviate from the list syntax? After all, lists and lists of lists are (in some sense) arrays, too.
On the other hand, talking about lists, there is the syntax `[1..10]`, which creates the list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Why is this the case when Python would ignore the 10? For example, `range(1, 10)` is equivalent to
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Even `srange(1, 10)` creates the same list, but with Sage `Integer`s, instead of Python's `int`s. Is there any good reason for having `[1..10]`be equivalent to `srange(1, 11)`?
Thanks in advance for your answers!dsejasMon, 18 Nov 2019 16:18:18 -0600http://ask.sagemath.org/question/48802/Why SageMath cannot inverte this matrix?http://ask.sagemath.org/question/48771/why-sagemath-cannot-inverte-this-matrix/Here is a list of three self-adjoint commuting matrices I would like to simultaneously diagonalize:
SageMath version 8.9, Release Date: 2019-09-29
sage: kk=QQ.algebraic_closure()
sage: L=[[[0,1,0,0,0,0,0,0],[1,4,0,1,1,1,1,0],[0,0,1,1,1,1,1,2],[0,1,1,1,1,1,1,2],[0,1,1,1,1,1,1,2],[0,1,1,1,1,1,1,2],[0,1,1,1,1,1,1,2],[0,0,2,2,2,2,2,3]],[[0,0,1,0,0,0,0,0],[0,0,1,1,1,1,1,2],[1,1,1,1,1,1,1,2],[0,1,1,2,1,1,1,2],[0,1,1,1,2,1,1,2],[0,1,1,1,1,2,1,2],[0,1,1,1,1,1,2,2],[0,2,2,2,2,2,2,3]], [[0,0,0,1,0,0,0,0],[0,1,1,1,1,1,1,2],[0,1,1,2,1,1,1,2],[1,1,2,0,0,2,3,2],[0,1,1,0,2,2,2,2],[0,1,1,2,2,1,1,2],[0,1,1,3,2,1,0,2],[0,2,2,2,2,2,2,4]]]
sage: M=[matrix(kk,l) for l in L]
sage: M
[
[0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0]
[1 4 0 1 1 1 1 0] [0 0 1 1 1 1 1 2] [0 1 1 1 1 1 1 2]
[0 0 1 1 1 1 1 2] [1 1 1 1 1 1 1 2] [0 1 1 2 1 1 1 2]
[0 1 1 1 1 1 1 2] [0 1 1 2 1 1 1 2] [1 1 2 0 0 2 3 2]
[0 1 1 1 1 1 1 2] [0 1 1 1 2 1 1 2] [0 1 1 0 2 2 2 2]
[0 1 1 1 1 1 1 2] [0 1 1 1 1 2 1 2] [0 1 1 2 2 1 1 2]
[0 1 1 1 1 1 1 2] [0 1 1 1 1 1 2 2] [0 1 1 3 2 1 0 2]
[0 0 2 2 2 2 2 3], [0 2 2 2 2 2 2 3], [0 2 2 2 2 2 2 4]
]
I applied the following process to find the appropriate change of basis matrix p:
sage: p=identity_matrix(kk,8)
sage: q=~p
sage: for m in M:
....: a=q*m*p
....: da, pa = a.jordan_form(transformation=True)
....: p=p*pa
....: q=~p
But the process does not finish (quickly enough, as expected), if I break it (Ctrl+C) after 5 minutes, I get:
sage: p
[1 1 1 1 1 1 1.000000000000000? 1]
[0 0 0 -0.2360679774997897? 4.236067977499789? -1 0 9]
[1 1 1 -1 -1 0 1.000000000000000? 10]
[-3.959901309262505? -0.4551399712853820? -0.3198201782016355? 0 0 1 1.734861458749522? 11]
[-1.747468453907949? 0.1971262975999527? 1.126757059617217? 0 0 1 -2.576414903309221? 11]
[1.441290910412462? 0.5668886275946296? -2.523095590631670? 0 0 1 -0.4850839473754211? 11]
[3.266078852757992? -1.308874953909201? 0.7161587092160885? 0 0 1 0.3266373919351204? 11]
[0 0 0 0.618033988749895? -1.618033988749895? -2 0 18]
[I removed spaces between entries for p being more readable]
and in fact the problem is that SageMath cannot inverte p, the following does not finish (after several hours):
sage: q=~p
whereas the matrix p is invertible:
sage: det(p)
97930.0?
**Questions**: What is the problem? How to solve it?
______________
By applying the answer of @rburing I get the following:
sage: sigma=K.embeddings(QQbar)[0]
sage: P=p.apply_map(sigma)
sage: P
[ 1 1 1 1 1 1 1 1]
[ 9 -1 0 0 0 0 0.?e7 0.?e7]
[ 10 0 1 1 1 1 -1 -1]
[ 11 1 0.?e7 0.?e7 0.?e6 0.?e8 0 0]
[ 11 1 0.?e8 0.?e7 0.?e7 0.?e7 0 0]
[ 11 1 0.?e8 0.?e7 0.?e8 0.?e7 0 0]
[ 11 1 0.?e8 0.?e7 0.?e7 0.?e8 0 0]
[ 18 -2 0 0 0 0 0.?e7 0.?e7]
sage: Q=q.apply_map(sigma)
sage: Q*M[0]*P
[ 9 0 0 0 0 0 0 0]
[ 0 -1 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0.?e7 0]
[ 0 0 0 0 0 0 0 0.?e7]
whereas
sage: M[0].eigenvalues()
[9, -1, 0, 0, 0, 0, -0.2360679774997897?, 4.236067977499789?]
How to make this method working better?Sébastien PalcouxSat, 16 Nov 2019 04:16:03 -0600http://ask.sagemath.org/question/48771/Bug when testing if a matrix is in SRhttp://ask.sagemath.org/question/48591/bug-when-testing-if-a-matrix-is-in-sr/On sagemath 8.9, I find the behavior of ``SR`` with matrix a bit strange.
sage: M = matrix([[0, -1], [1, 0]])
sage: print(SR(M)+M)
[[ 0 -1]
[ 1 0] -1]
[ 1 [ 0 -1]
[ 1 0]]
What is the use of coercing a matrix to the symbolic ring if it cannot be used as a matrix afterward?
These two lines of code also both raise an attribute error:
sage: SR(M) == M
sage: M in SR
AttributeError: 'ComplexIntervalField_class_with_category' object has no attribute 'complex_field'
By itself, it is not very relevant, but some element constructors (e.g. ``lie_algebra``) contain a line
if x in self.base_ring():
do something
which means ``SR`` cannot be used as a base ring.
Is this a known bug?
A workaround would be to add a single line in ``SR.__contains__`` to return false when ``x`` is matrix (or maybe there are case when a matrix is considered in ``SR``, I don't know), but this would not solve the underlying issues.Florentin JaffredoSat, 02 Nov 2019 11:09:26 -0500http://ask.sagemath.org/question/48591/vector equation solvehttp://ask.sagemath.org/question/48532/vector-equation-solve/How to solve this?:
F = vector([cos(alpha),sin(alpha),z])
G = vector([z,cos(alpha),sin(alpha)])
A = vector([0,0,0])
solve(F-G == A)
Answer must be:
[cos(asin(cos(alpha))),
sin(asin(cos(alpha))),
sin(alpha)]dimonbavlyMon, 28 Oct 2019 04:39:17 -0500http://ask.sagemath.org/question/48532/Finding short vectors kernelhttp://ask.sagemath.org/question/8625/finding-short-vectors-kernel/I am looking for quadratic forms with a given point - so I want short integer vectors which are perpendicular to
v=[X*X,X*Y,X*Z,X*T,Y*Y,Y*Z,Y*T,Z*Z,Z*T,T*T]
for (in this case) [X,Y,Z,T]=[4423,7583,8765,3459]
This sounds like a problem with LLL written all over it, so I do
L=[[Y,-X,0,0,0,0,0,0,0,0],[0,Z,-Y,0,0,0,0,0,0,0],[0,0,T,-Z,0,0,0,0,0,0],[0,0,0,Y*Y,-X*T,0,0,0,0,0],[0,0,0,0,Z,-Y,0,0,0,0],
[0,0,0,0,0,T,-Z,0,0,0],[0,0,0,0,0,0,Z*Z,-Y*T,0,0],[0,0,0,0,0,0,0,T,-Z,0],[0,0,0,0,0,0,0,0,T,-Z]]
M=matrix(L)
M.lll()
but this gives an error message AttributeError: 'sage.matrix.matrix_integer_dense.Matrix_integer_dense' object has no attribute 'lll'fivemackFri, 13 Jan 2012 10:39:28 -0600http://ask.sagemath.org/question/8625/Why GF(256) matrix only have zero and one number?http://ask.sagemath.org/question/47379/why-gf256-matrix-only-have-zero-and-one-number/like this
sage: matrix(GF(2**8), [1, 2, 3, 4])
[1 0 1 0]
I just want do some matrix calculate mod 256, can any help me, please?helicaSun, 04 Aug 2019 06:27:35 -0500http://ask.sagemath.org/question/47379/can't display the inverse of complex matrixhttp://ask.sagemath.org/question/47326/cant-display-the-inverse-of-complex-matrix/ Hi
it seems that Sagemath is able to calculate this matrix inverse, but it is unable to display it.
Maybe someone will explain me why ? it is not easy to find what I do wrong because there is no error message for n=8
an it's ok for n=4
#FFT
w=var('w')
n=8
FFT=matrix(SR,n,n)
#show (FFT)
for i in (0..n-1):
for j in (0..n-1):
FFT[i,j]=w^(i*j)
FFTc=1/sqrt(n) *FFT.subs(w=e^(2*I*pi/n))
#show(" FFTc : ",FFTc)
FFTc.change_ring(CC)
show(" FFTc.right_kernel().matrix() : ",FFTc.right_kernel().matrix())
show (" FFTc.determinant() for n =",str(n),": ",FFTc.determinant())
FFTcI=copy(FFTc).inverse()
#show (" FFT w :",FFT)
show (" FFTc with w=e^(2*I*pi/",str(n),") : ",FFTc)
show (" FFTc inverse with w=e^(2*I*pi/",str(n),") : ",FFTcI)
ortolljWed, 31 Jul 2019 11:19:16 -0500http://ask.sagemath.org/question/47326/Matrix multiplication of sparse matrix with matrix over polynomial ringhttp://ask.sagemath.org/question/47196/matrix-multiplication-of-sparse-matrix-with-matrix-over-polynomial-ring/ Hi all,
I would like to know how to multiply the following matrices I have constructed in Sage. Here is my code for a toy example:
from scipy.sparse import csr_matrix
row = [0,0,1]
col = [0,1,1]
data = [1,-1,1]
A = csr_matrix((data,(row,col)),shape=(4,4))
R.<x,y> = PolynomialRing(QQ,2)
B = matrix(R,2,2,[1,x,1,y])
When I try to multiply the matrices using A.dot(B), I end up with the error: "No supported conversion for types: (dtype('int64'), dtype('O'))"
Is there a way I can multiply these matrices and yield an output that is a csr_matrix? (I suspect I would want to convert the entries of my A matrix to be the same data type, but I am unaware of how to do this)
Thank you for your time!
BarkWed, 17 Jul 2019 10:49:28 -0500http://ask.sagemath.org/question/47196/How to generate a nonsquare Vandermonde matrix?http://ask.sagemath.org/question/47122/how-to-generate-a-nonsquare-vandermonde-matrix/ According to the [documentation](http://doc.sagemath.org/html/en/reference/matrices/sage/matrix/special.html#sage.matrix.special.vandermonde), we can generate a Vandermonde matrix using the method matrix.vandermonde() or vandermonde().
But they generate only square matrix. How do we generate a Vandermonde matrix which is not a square matrix?qbyteThu, 11 Jul 2019 03:13:46 -0500http://ask.sagemath.org/question/47122/Testing if the entries of a matrix of rational vectors are actually integershttp://ask.sagemath.org/question/46929/testing-if-the-entries-of-a-matrix-of-rational-vectors-are-actually-integers/I moved from Python to SageMath because it allows me to deal with natural operations in mathematics without having to reinvent the wheel through typing obvious classes and methods. I also suppose the built-in classes and methods do things in more efficient ways that I could do myself.
However, sometimes I find hard to find the right function or class for what I want to do.
I have created several matrices using 'matrix' which may have rational or integer numbers (so I use QQ to define them). I want to check which matrices actually have all entries as integers. I know how to do this by looping through all entries of each matrix and calling 'is_integer', but is there an existing method in 'matrix' doing this for me? I could not find one.
Jesus Martinez GarciaTue, 18 Jun 2019 04:58:39 -0500http://ask.sagemath.org/question/46929/Matrix projection blueshttp://ask.sagemath.org/question/46779/matrix-projection-blues/Hi
on OpenCourseware MIT site:
[Lecture 15: Projections onto subspaces](https://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/video-lectures/lecture-15-projections-onto-subspaces/)
[edited :the code on sagecell sagemath org was not the good one ! it was the first version I wrote.
when I updated the code in the cell, that does not work, I had to open a new cell]
[code on sagecell sagemath org ](https://sagecell.sagemath.org/?z=eJytVMFuozAQvfsrRvQQHNykkKaHlXwAqYeVshKVcogURSsDDvGW2Ajclu7Xrw2UkKbpaW_DzLw38-Y5YSu6XZDlDgBuIFWqyoRkmtdQiFrDK0-1qoChxLbNA3K_-6YtQcWKLueBadmzNsObkslaKAlaQSbqsmDvUPHMwCQHIYcBpliZ0HQidAMHXnH4CSxTpQZ94GaifOXSlk1rjxG1iVNVvBwlHJmuRINC2gXu0xNhKzzTlZleqpq72OzU14LGxygadSbfdt5AXKk_3W7wqy0AgZQVhZGxsRrsgq8i4wpt5MuRhjAFNxwznighaAK0ybikrnvRNIUQ8CzjukPUZgar0IZa1rkFjTcLMKoP6s11DOgHOCQk4EDUhpENLaj9skGbsARtwgRtovvCKPeptcPdbm-L1ZTD3hpnhYUz666Ld2R7pbAjUPCcy-x3wRJe0ImxpDydy9JOhhbjlaroxNg_IaPYLBDQslDa7Yx1I9yXnbziXDrkTWT6QJfk06iPV3cxoYVZ3sUZbzjwJgVLnz94F1d4wwveFmZ42RooaN5o12EO-czet5G9kroWfzkN7jBKTpBkgAxC-43PITHdTKPxy_H_k-PEgbiNYgBzpPuzI8UjGS_GvCu37002P4H-WvEX1zJ4jMqT8nJQHuOpP7tbno8a1C-M-kca3cbn6vNltymrKnOGeJYqvt-LVJg_htrFJPqc6MlLIZ-v6ui3v3ylLQpjxE_r82H9RzwPvK-ldNPOjGxdy30vD7x84eX3Xr702NpL1l659via7EXe9roPBB4waY5C0tvhiWzvdibFGjrOeAvyPsqFeOvvPN_kLNTH_wDXithb&lang=sage&interacts=eJyLjgUAARUAuQ==)
Q1:
p is the b projected vector on vector a
below all letters are matrices
E=B-P with P=X*A
E=B-X*A as E perpendicular to A => dot product(A,E)) = 0 means A.transpose()*E=0
then A^T*(B-X*A)=0 so A^T*(X*A)=A^T*B (and this is false !)
but Gilbert Strang write X*A^T*A=A^T*B (and this is good !)
but we are not allowed to commute A^T*X*A by X*A^T*A if X is a matrix !
I know I made a mistake in my raisonning but I fail to find it !
Q2 : Why I must write X=A * (A.transpose())/(( (A.transpose()) * A ).det())
instead of X=A * (A.transpose())/(( (A.transpose()) * A ))
why I need to add .det() ?ortolljMon, 03 Jun 2019 12:31:17 -0500http://ask.sagemath.org/question/46779/General 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/