0

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?

3 Answers 3

3

is it OK to just use NumPy?

import numpy as np

def square_matrix(size, *elements):
    return np.array(elements).reshape(size, size)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it's fine, I just couldn't figure out a way to implement this with NumPy.
0

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)]

Comments

0

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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.