Home > Mobile >  How to get Matrix using numpy
How to get Matrix using numpy

Time:10-14

I want to make matrix like below using numpy

matrix_example = [[1, 1, 1, 1, 1, 1, 1, 1, 1],
                  [1, 0, 0, 0, 0, 0, 0, 0, 1],
                  [1, 0, 1, 1, 1, 1, 1, 0, 1],
                  [1, 0, 1, 0, 0, 0, 1, 0, 1],
                  [1, 0, 1, 0, 1, 0, 1, 0, 1],
                  [1, 0, 1, 0, 0, 0, 1, 0, 1],
                  [1, 0, 1, 1, 1, 1, 1, 0, 1],
                  [1, 0, 0, 0, 0, 0, 0, 0, 1],
                  [1, 1, 1, 1, 1, 1, 1, 1, 1]]

my Idea is using np.where but It doesn't work well..
I want hint about generate matrix like that.

my second idea is

  1. make 9 by 9 matrix fill with zero using numpy.zeros([9, 9])
  2. change 0 to 1 where index is include 0, 2, 4.

CodePudding user response:

a2D = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 0, 0, 0, 0, 0, 0, 0, 1],[1, 0, 1, 1, 1, 1, 1, 0, 1],[1, 0, 1, 0, 0, 0, 1, 0, 1],[1, 0, 1, 0, 1, 0, 1, 0, 1],[1, 0, 1, 0, 0, 0, 1, 0, 1],[1, 0, 1, 1, 1, 1, 1, 0, 1],[1, 0, 0, 0, 0, 0, 0, 0, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1]])

try this

CodePudding user response:

you can use np.ones and np.zeros to do it like:

first_mat = np.ones([9, 9])
second_mat = np.zeros([7, 7])
third_mat = np.ones([5, 5])
forth_mat = np.zeros([3, 3])

first_mat[1:-1, 1:-1] = second_mat
first_mat[2:-2, 2:-2] = third_mat
first_mat[3:-3, 3:-3] = forth_mat
first_mat[4:-4, 4:-4] = 1

and this will give you your output, it maybe not the easiest way, but I hope it can help, and of course first_mat is the maxrix you need

CodePudding user response:

There's already a np.matrix function that makes what you probably want

For you example, it should be as easy as

my_matrix = np.matrix(matrix_example)

Have a look at the official documentation for further info :)
https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

CodePudding user response:

Inspired by Mohamed Yahya's answer and generalizing it to any number of "squares":

import numpy as np


def cool_matrix(squares):
    final_matrix = np.zeros((squares * 2 - 1, squares * 2 - 1), dtype=np.int)

    for square in range(squares, 0, -1):
        square_dimensions = (square * 2 - 1, square * 2 - 1)
        if square % 2 == 0:
            curr_square = np.zeros(square_dimensions, dtype=np.int)
        else:
            curr_square = np.ones(square_dimensions, dtype=np.int)

        offset = squares   square - 1
        final_matrix[-offset:offset, -offset:offset] = curr_square
    return final_matrix


print(cool_matrix(5))

output is:

[[1 1 1 1 1 1 1 1 1]
 [1 0 0 0 0 0 0 0 1]
 [1 0 1 1 1 1 1 0 1]
 [1 0 1 0 0 0 1 0 1]
 [1 0 1 0 1 0 1 0 1]
 [1 0 1 0 0 0 1 0 1]
 [1 0 1 1 1 1 1 0 1]
 [1 0 0 0 0 0 0 0 1]
 [1 1 1 1 1 1 1 1 1]]
  • Related