How to construct the following matrix
How we can construct the following n×n matrix A=(aij) such that aij=1 when j−i≡1 mod n; aij=−1 when j−i≡-1 mod n and aij=0 otherwise. I need for n=10.
How we can construct the following n×n matrix A=(aij) such that aij=1 when j−i≡1 mod n; aij=−1 when j−i≡-1 mod n and aij=0 otherwise. I need for n=10.
Here are a few ways to produce this matrix. One could think of many more ways.
I'll use n=5 to save space. Adapt to n=10.
sage: n = 5
This may be the more efficient:
sage: matrix.circulant([0, 1] + [0] * (n - 3) + [-1])
[ 0 1 0 0 -1]
[-1 0 1 0 0]
[ 0 -1 0 1 0]
[ 0 0 -1 0 1]
[ 1 0 0 -1 0]
Using a lambda function:
sage: a = matrix(ZZ, n, lambda i, j: ((j - i) % n == 1) - ((i - j) % n == 1))
sage: a
[ 0 1 0 0 -1]
[-1 0 1 0 0]
[ 0 -1 0 1 0]
[ 0 0 -1 0 1]
[ 1 0 0 -1 0]
More by hand:
sage: a = matrix(ZZ, n, [[((j - i) % n == 1) - ((i - j) % n == 1) for j in range(n)] for i in range(n)])
sage: a
[ 0 1 0 0 -1]
[-1 0 1 0 0]
[ 0 -1 0 1 0]
[ 0 0 -1 0 1]
[ 1 0 0 -1 0]
A variation, maybe slower because of the matrix subtraction.
sage: b = matrix(ZZ, n, [[(j-i)%n == 1 for j in range(n)] for i in range(n)])
sage: a = b - b.T
sage: a
[ 0 1 0 0 -1]
[-1 0 1 0 0]
[ 0 -1 0 1 0]
[ 0 0 -1 0 1]
[ 1 0 0 -1 0]
One might also prefer to produce a sparse matrix.
sage: b = matrix(ZZ, n, {(i, (i+1) % n): 1 for i in range(n)})
sage: c = matrix(ZZ, n, {((i + 1) % n, i): 1 for i in range(n)})
sage: a = b - c
sage: a
[ 0 1 0 0 -1]
[-1 0 1 0 0]
[ 0 -1 0 1 0]
[ 0 0 -1 0 1]
[ 1 0 0 -1 0]
sage: a.parent()
Full MatrixSpace of 10 by 10 sparse matrices over Integer Ring
Why are there elements in the top right and bottem left corner of the matrix?
Thank you for your answer. It is correct
Asked: 6 years ago
Seen: 762 times
Last updated: Mar 15 '19