Dhyey Shah
Dhyey Shah

Reputation: 25

Python function for creating a square matrix of any size

I need to create a function which can take an unspecified number of parameters (elements for the matrix) and return the corresponding square matrix. I have implemented this using the following approach.

def square_matrix(size, *elements):

    numbers = list(elements)
    if size ** 2 != len(numbers):
        return "Number of elements does not match the size of the matrix"
    else:
        matrix = []
        factor = 0
        for i in range(0, size):
            row = []
            for j in range(factor * size, (factor + 1) * size):
                row.append(numbers[j])
            factor += 1
            matrix.append(row)
            i += 1
        return matrix

print(square_matrix(3, 1, 2, 3, 4, 5, 6, 7, 8, 9))
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Although this method works fine for smaller matrices, it seems somewhat inefficient as it uses nested loops and appears unnecessarily long to me. Is there any better/concise way of implementing the same?

Upvotes: 0

Views: 12297

Answers (3)

BioGeek
BioGeek

Reputation: 22847

There is no need to give the size as an argument. If the square root of the length of the arguments is a whole number, then you can make a square matrix of the elements.

import numpy as np
from math import sqrt

def square_matrix(*elements):
    size = sqrt(len(elements))
    if size.is_integer():
      return np.array(elements).reshape(int(size), int(size))
    else:
      raise RuntimeError("Number of elements is not sufficient to make a square matrix")


print(square_matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
# Output:
# array([[1, 2, 3],
#        [4, 5, 6],
#        [7, 8, 9]])

Upvotes: 0

Kazmer Nagy-Betegh
Kazmer Nagy-Betegh

Reputation: 1

For the matrix creation, you could use list comprehension which is more efficient than a for a loop.

You could replace the for loops in the else part of your if statement by the below code.

matrix = [[i for i in elements[j:j+size]] for j in range(0,len(elements),size)]

Upvotes: 0

janus235
janus235

Reputation: 1521

is it OK to just use NumPy?

import numpy as np

def square_matrix(size, *elements):
    return np.array(elements).reshape(size, size)

Upvotes: 3

Related Questions