Python matrix with a cross of numbers

summarizing an exercise in matrix data manipulation
2025-11-15 11:15
// updated 2025-11-16 13:26

Using Python and NumPy, we can create an (n x n) matrix with a "cross-shaped" figure composed of any integer t:

import numpy as np

# make an (n x n) matrix with a "cross" (+) of any integer t

def cross(n, t):

  # identify the middle indices
  mid = n // 2
  mids = [mid] if n % 2 else [mid - 1, mid]

  # make a zero matrix first
  a = np.zeros((n,n), dtype='int')

  # a[:,i] means all rows for the column at index i
  a[:,mids] = t

  # a[i,:] means all columns for the row at index i
  a[mids,:] = t

  return a

print(cross(5, 5))

Implications?

We can take a table of zeroes ... and transform entire rows and columns into any value, with some simple index range operations, i.e.:

  • a[:,column] to change a column
  • a[row,:] to change a row)
⬅️ older (in snippets)
🐍 Python solution: finding the day of the week
⬅️ older (posts)
🎓 On the good school