Home > Back-end >  A function that returns ones at the boundary of a matrix
A function that returns ones at the boundary of a matrix

Time:11-17

I just started learning the numpy library and I have a question.

I wrote a function decorate_matrix that takes one integer greater than one as input. The function should return an n by n matrix with 1's on the edges and 0's at all other positions.

My code:

import numpy
def decorate_matrix(n: int):
    matrix = numpy.zeros((n, n))
    matrix[0] = numpy.full(n, 1)
    matrix[n - 1] = numpy.full(n, 1)
    matrix = matrix.transpose()
    matrix[0] = numpy.full(n, 1)
    matrix[n - 1] = numpy.full(n, 1)
    return matrix

n = int(input())
decorate_matrix(n)

I want to know if there is something in the numpy library to do this without matrix transposition, or is this the best option?

CodePudding user response:

I like your implementation, there's nothing wrong with it and it's clever. But if you're goal is to not use transpose, then you could do this

def decorate_matrix(n: int):
    matrix = numpy.zeros((n, n))
    matrix[:,0]=1   # first column
    matrix[0,:]=1   # first row
    matrix[:,-1]=1  # last column
    matrix[-1,:]=1  # last row
    return matrix
  • Related