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

时间:2018-01-14 23:04:48

标签: 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]

我创建了一个生成零矩阵的类,并用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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]])

答案 2 :(得分:0)

我更喜欢根据索引的mod制作一个过滤器,乘以一个随机+ -1矩阵。 E.g:

def my_matrix(N=10, toggle=0):

    m       = np.random.choice([-1, 1], (N, N))
    [j,k]   = np.indices([N,N])
    filter  = (j + k + toggle)%2

    return filter*m

答案 3 :(得分:0)

填充随机和归零的内容,我用零填充并输入随机值

def matrix_lattice(self):
    self.lattice = np.zeros((N, N))
    self.lattice[::2,   ::2] = np.random.choice([-1, 1], (-(-N // 2), -(-N // 2)))
    self.lattice[1::2, 1::2] = np.random.choice([-1, 1], (N // 2,     N // 2)))

答案 4 :(得分:-3)

Parameter           Description
---------------------------------------------------------------------------
CallStatus          A descriptive status for the call. The value is one of queued, initiated, ringing, in-progress, busy, failed, or no-answer.
CallDuration        The duration in seconds of the just-completed call. Only present in the completed event.
SipResponseCode     The SIP code that resulted in a failed call. For instance 404 for a number that was unreachable or 487 if the Timeout value was reached before the call connected. Only present in the completed event if the CallStatus is failed or no-answer.
RecordingUrl        The URL of the phone call's recorded audio. This parameter is included only if Record=true is set on the REST API request and does not include recordings initiated in other ways. RecordingUrl is only present in the completed event. The recording file may not yet be accessible when the Status Callback is sent. Use RecordingStatusCallback for reliable notification on when the recording is available for access.
RecordingSid        The unique ID of the Recording from this call. RecordingSid is only present in the completed event.
RecordingDuration   The duration of the recorded audio (in seconds). RecordingDuration is only present in the completed event. To get a final accurate recording duration after any trimming of silence, use RecordingStatusCallback.
Timestamp           The timestamp when the event was fired, given as UTC in RFC 2822 format.
CallbackSource      A string that describes the source of the webhook. This is provided to help disambiguate why the webhook was made. On Status Callbacks, this value is always call-progress-events.
SequenceNumber      The order in which the events were fired, starting from 0. Although events are fired in order, they are made as separate HTTP requests and there is no guarantee they will arrive in the same order.

然后在Python(3.6)中:

#!/usr/bin/env python

import numpy as np 
import random

class SpecialMat:
    def __init__(self, m, n):
        self.dim = (m, n)  # matrix dimension
        self.members = (-1, 1)
        self.data = self.__matrix_lattice(self)

    def display(self):
        print(self.data)

    @staticmethod
    def __matrix_lattice(self):
        m = self.dim[0]
        n = self.dim[1]
        L = self.members
        a = np.zeros((m, n), dtype=int)
        for i in range(m):
            for j in range(n):
                if self._is_odd(j + i):
                    a[i, j] = random.choice(L)
        return a

    def _is_odd(self, num):
        return num % 2 is not 0

from <yourPythonFileName> import SpecialMat M = SpecialMat(10, 5) # should work with any integers M.display() [[ 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] [ 0 1 0 1 0 1 0 -1 0 -1]] 来自here