IsaacB
IsaacB

Reputation: 11

List > numpy.ndarray using np.array(list) not working in class __init__ . Problem with numpy?

I'm currently building a class called 'system' that takes in 4 arguments: A, B, C, D which are matrices of a state-space system.

The intent is that the user can input these using nested built-in <class 'list'> types, such as [[1, 0],[0, 1]].

The __init__ method of the class should take these lists and convert them to NumPy arrays of type <class 'np.ndarray'> using np.array() and store them as self.A, self.B ... etc.

However, after completing the np.array() operation, on checking the type of these objects using print(type(self.A)), the console prints <class 'list'>.

I'm not sure how this can be possible since I have clearly defined them as numpy arrays. I have searched online and asked ChatGPT but I haven't been able to find an answer that might explain why this is happening. Could this be to do with NumPy? Or have I seriously misunderstood the way the Python class constructor functions?

The script I am running (all variables cleared) :

import numpy as np


class system():
    def __init__(self, A, B=None, C=None, D=None):
        self.A = np.array(A)
        self.B = np.array(B)
        self.C = np.array(C)
        self.D = np.array(D)

        print(type(A))

        assert self.A.shape[0] == self.A.shape[1], 'System matrix (A) not square'
        assert self.A.shape[0] == self.B.shape[0], 'Number of rows of A does not match number of rows of B'

    def fxKutta(self, X, U):

        X = np.array(X).reshape(-1, 1)
        U = np.array(U).reshape(-1, 1)

        assert X.shape[0] == self.A.shape[0], 'Number of rows of X does not match number of rows of A'
        assert U.shape[0] == self.B.shape[0], 'Number of rows of U does not match number of rows of B'

        Xdot = self.A @ X + self.B @ U

        return Xdot


A = [[1, 1], [1, 1]]
B = [[1], [1]]

sys = system(A, B)

The console after running :

<class 'list'>

#====================================================

I tried passing the arrays through another variable :

def __init__(self, A, B=None, C=None, D=None):
        matA = np.array(A)
        A = np.array(matA)

... which did not work. This would not have been a clean solution anyway.

Upvotes: 0

Views: 58

Answers (1)

Ammar
Ammar

Reputation: 192

You are checking the type of passed argument A in this case which you passed into your class as a list. If you check the type of your instance variable, self.A in this case, it will result to <class 'numpy.ndarray'>

Upvotes: 0

Related Questions