Matrix Configuration Question (matrix values between matrix values at specific coordinates)

Asked 2 years ago, Updated 2 years ago, 59 views

Hello, I'm a student studying Python.

I'm writing the code that makes up the matrix I have a question because there's a traffic jam TT

If there's a matrix like picture number one, I want to construct a matrix by randomly adding a value of 1 where 0 is currently located I want to construct a matrix that is unconditionally connected by 1.

For example, I want to organize a matrix to connect to 1 like pictures 2 and 3 but I'm at a loss...If you've tried similar coding or if you can give me a hint about I'd really appreciate it! Thank you

matrix python

2022-09-20 08:56

1 Answers

Code that converts all zeros to one.

>>> import numpy as np

>>> grid = np.zeros((5, 5))
>>> grid
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
>>> grid[:2, :2] = 2
>>> grid[4:, 4:] = 2
>>> grid
array([[2., 2., 0., 0., 0.],
       [2., 2., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 2.]])
>>> grid[grid == 0] = 1
>>> grid
array([[2., 2., 1., 1., 1.],
       [2., 2., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 2.]])


2022-09-20 08:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.