# How to construct the following matrix

How we can construct the following $n\times n$ matrix $A=(a_{ij})$ such that $a_{ij}= 1$ when $j-i\equiv$1 mod $n$; $a_{ij}= -1$ when $j-i\equiv$-1 mod $n$ and $a_{ij}=0$ otherwise. I need for $n=10$.

edit retag close merge delete

Sort by » oldest newest most voted

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

more

Why are there elements in the top right and bottem left corner of the matrix?

( 2019-03-15 10:55:09 +0200 )edit

( 2019-03-15 11:42:48 +0200 )edit

## Stats

Seen: 118 times

Last updated: Mar 15 '19