Home > Back-end >  Given n. Create an nXn matrix with the following structure?
Given n. Create an nXn matrix with the following structure?

Time:05-03

Given n. Create an nXn matrix with the following structure: On the main diagonal, 1 and 2 alternate. Further from each cell of the main diagonal to the right and down, the same numbers are placed as in this cell itself.

The matrix should look like this:

1 1 1 1 1 1
1 2 2 2 2 2
1 2 1 1 1 1
1 2 1 2 2 2
1 2 1 2 1 1
1 2 1 2 1 2

CodePudding user response:

Your actual result putting a 1 where min(row, column) is even, and 2 where it is odd.

So

x = np.array(range(10))
y = np.minimum(x, x[:, None])
result = y % 2   1

CodePudding user response:

One simple method is to use an indicator function to tell if you're in a 1-cell or a 2-cell. Note that min(i, j) increases linearly with those arrow shapes (moving from top-left to bottom-right in the matrix), so min(i, j) & 1 corresponds exactly to 0 for 1-cells and 1 for 2-cells.

result = 1   (np.min(np.indices((n, n)), axis=0) & 1)

Or in vanilla Python:

result = [[1   (min(i, j) & 1) for i in range(n)] for j in range(n)]

CodePudding user response:

You can create a matrix of ones, and then create a for loop to add in the twos:

import numpy as np

result = np.ones((6, 6))

for idx in range(1, result.shape[0], 2):
    result[idx, idx::] = 2
    result[idx::, idx] = 2

print(result)

This outputs:

[[1. 1. 1. 1. 1. 1.]
 [1. 2. 2. 2. 2. 2.]
 [1. 2. 1. 1. 1. 1.]
 [1. 2. 1. 2. 2. 2.]
 [1. 2. 1. 2. 1. 1.]
 [1. 2. 1. 2. 1. 2.]]
  • Related