创建交替的零和随机数矩阵?

The*_*Dig 3 python numpy matrix

我正在尝试编写一些代码来创建一个交替的1/-1和0的矩阵,即:

[-1  0 -1  0  1  0  1  0 -1  0]
[ 0  1  0 -1  0  1  0 -1  0  1]
[ 1  0  1  0 -1  0 -1  0 -1  0]
[ 0  1  0 -1  0 -1  0 -1  0  1]
[ 1  0  1  0  1  0  1  0  1  0]
Run Code Online (Sandbox Code Playgroud)

我创建了一个生成零矩阵的类,并用1或-1附加它,我已经尝试弄乱我的for循环和切片我的矩阵但我似乎无法生成我喜欢的矩阵.我有一个中级的python知识,所以我很欣赏使用我创建的代码解决我的问题可能不是特别优雅,但任何帮助将不胜感激.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import random


#constants
N = 10 #dimensions of matrix


class initial_lattice: 
    def __init__(self,N):   #create initial matrix of size NxN
        self.N=N
        self.matrix_lattice()

    def matrix_lattice(self):
        self.lattice = np.zeros((N,N), dtype=int) #creates initial matrix of zeroes
        for x in range(0,N):    
            for y in range(0,N):
                self.lattice[x,y]=random.choice([1,-1]) #randomly chooses values of 1 and -1 and appends matrix

lattice1=initial_lattice(N) 


print lattice1.lattice
Run Code Online (Sandbox Code Playgroud)

f5r*_*e5d 7

偶数/奇数行的想法似乎很好,一个变化:

def matrix_lattice(self):
    self.lattice = np.random.choice([-1, 1], (N, N))
    self.lattice[::2, ::2] = 0
    self.lattice[1::2, 1::2] = 0
Run Code Online (Sandbox Code Playgroud)


DYZ*_*DYZ 5

可能有更好的解决方案,但这个肯定有效:

def matrix_lattice(m,n):
  mask = np.ones((m,n), dtype=int) # All 1s
  mask[1::2, ::2] = 0 # Clean even fields in odd rows
  mask[::2, 1::2] = 0 # Clean odd fields in even rows
  u = np.random.randint(2, size=(m,n)) * 2 - 1 # 1s and -1s      
  return u * mask # Superimpose the matrices

print(matrix_lattice(5,5))
#array([[-1,  0,  1,  0,  1],
#       [ 0, -1,  0,  1,  0],
#       [ 1,  0,  1,  0, -1],
#       [ 0,  1,  0, -1,  0],
#       [ 1,  0, -1,  0, -1]])
Run Code Online (Sandbox Code Playgroud)