1 Generate Matrix from Arrays

Go to the RMD, PDF, or HTML version of this file. Go back to Python Code Examples Repository (bookdown site) or the pyfan Package (API).

import numpy as np

1.1 Generate a Random Matrix

Generate a matrix with random numbers and arbitrary number of rows and columns. Several types of matrix below:

  1. uniform random
  2. integer random
  3. integer random resorted (shuffled)
  4. integer random redrawn (with replacements)

Set size:

it_rows = 2;
it_cols = 3;
np.random.seed(123)

uniform random:

# A random matrix of uniform draws
mt_rand_unif = np.random.rand(it_rows, it_cols)
print(mt_rand_unif)
## [[0.69646919 0.28613933 0.22685145]
##  [0.55131477 0.71946897 0.42310646]]

integer random:

# A random matrix of integers
it_max_int = 10
mt_rand_integer = np.random.randint(it_max_int, size=(it_rows, it_cols))
print(mt_rand_integer)
## [[6 1 0]
##  [1 9 0]]

integer random resorted (shuffled):

# A sequence of numbers, 1 to matrix size, resorted, unique
it_mat_size = it_rows*it_cols
ar_seq = np.arange(it_mat_size)
ar_idx_resort = np.random.choice(np.arange(it_mat_size), it_mat_size, replace = False)
ar_seq_rand_sorted = ar_seq[ar_idx_resort]
mt_seq_rand_sorted = ar_seq_rand_sorted.reshape((it_rows, it_cols))
print(mt_seq_rand_sorted)
# achieve the same objective with a shuffle
## [[5 4 2]
##  [3 1 0]]
np.random.shuffle(ar_seq)
mt_seq_rand_shuffle = ar_seq.reshape((it_rows, it_cols))
print(mt_seq_rand_shuffle)
## [[2 1 3]
##  [5 0 4]]

integer random redrawn (with replacements):

# A sequence of numbers, 1 to matrix size, resorted, nonunique, REPLACE = TRUE
it_mat_size = it_rows*it_cols
ar_seq = np.arange(it_mat_size)
ar_idx_resort_withreplacement = np.random.choice(np.arange(it_mat_size), it_mat_size, replace = True)
ar_seq_rand_sorted_withreplacement = ar_seq[ar_idx_resort_withreplacement]
mt_seq_rand_sorted_withreplacement = ar_seq_rand_sorted_withreplacement.reshape((it_rows, it_cols))
print(mt_seq_rand_sorted_withreplacement)
## [[3 2 4]
##  [2 4 0]]

1.2 Stack Arrays to Matrix

Given various arrays, generate a matrix by stacking equi-length arrays as columns

# three arrays
ar_a = [1,2,3]
ar_b = [3,4,5]
ar_c = [11,4,1]

# Concatenate to matrix
mt_abc = np.column_stack([ar_a, ar_b, ar_c])
print(mt_abc)
## [[ 1  3 11]
##  [ 2  4  4]
##  [ 3  5  1]]