Home > Software engineering >  ValueError: malformed node or string
ValueError: malformed node or string

Time:12-17

I am not sure why I cannot use np.matrix or a matrix like the following:

import numpy as np

A = np.matrix('3 -5; 2 7')
print(A)
B = np.matrix('13; 81')
print(B)
A_det = np.linalg.det(A)
print(A_det)
X_m = np.matrix(A)
X_m[:, 0] = B
print(X_m)
Y_m = np.matrix(A)
Y_m[:, 1] = B
print(Y_m)
x = np.linalg.det(X_m) / A_det
y = np.linalg.det(Y_m) / A_det

print(x)
print(y)
X = np.matrix('x; y')
O = A @ X - B 
print(O)

I keep getting this error:

ValueError                                Traceback (most recent call last)
Cell In[38], line 19
     17 print(x)
     18 print(y)
---> 19 X = np.matrix('x; y')
     20 O = A @ X - B 
     21 print(O)

ValueError: malformed node or string on line 1: <ast.Name object at 0x2dc0210>

CodePudding user response:

From the documentation on np.matrix:

If data is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows.

This means the data passed in the string, must be literals (1, or 1.5) not variables (or names).

Use an f-string instead:

X = np.matrix(f'{x}; {y}')

The error:

ValueError: malformed node or string on line 1: <ast.Name object at 0x2dc0210>

you are getting is because numpy is using ast.literal_eval to create the matrix (see here).

CodePudding user response:

You're trying to create a matrix using a string. That is wrong

Here is how that should be

...

print(x)
print(y)
X = np.matrix(f'{x}; {y}')  # change x and y for their values
O = A @ X - B 
print(O)

CodePudding user response:

The variables x and y haven't been initialized yet. Try below code instead

import numpy as np
A = np.matrix('3 -5; 2 7')
print(A)
B = np.matrix('13; 81')
print(B)
A_det = np.linalg.det(A)
print(A_det)
X_m = np.matrix(A)
X_m[:, 0] = B
print(X_m)
Y_m = np.matrix(A)
Y_m[:, 1] = B
print(Y_m)
x = np.linalg.det(X_m) / A_det
y = np.linalg.det(Y_m) / A_det

print(x)
print(y)
X = np.matrix([[x], [y]])
O = A @ X - B 
print(O)
  • Related