rohit rasam
rohit rasam

Reputation: 19

Not able to slice a numpy array

import numpy as np

n = int(input("Enter number of equations: "))
# Initialize matrix
print("Enter the values row-wise with the solution matrix of the coefficient matrix: ")

# For user input
a = np.array([[float(x) for x in input().split()] for y in range(n)])
b = np.array([float(y) for y in input().split()])[np.newaxis]
n = np.size(b)
b = b.T
sol = []
for i in range(n):
    sol = np.concatenate((a, b), axis=1)
    print(sol.round(decimals=4))
    for j in range(i+1, n):
        r = a[j][i] / a[i][i]
        a[j, :] = a[j, :] - (r * a[i, :])
        b[j] = b[j] - (r * b[i])
# Error part 
z = np.zeros((1, 3))
print(z)
for k in range(n-1, -1, -1):
    z[0, k] = (b[k] - (z[0, k] * a[k, k:])) / a[k, k]

print(z)

Error trace back:

TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/Rohit Rasam/Python Programs/NMO/GaussElimination.py", line 24, in <module>
    z[0, k] = (b[k] - (z[0, k] * a[k, k:])) / a[k, k]
ValueError: setting an array element with a sequence.

Upvotes: 0

Views: 49

Answers (1)

Ehsan
Ehsan

Reputation: 12417

In the line

z[0, k] = (b[k] - (z[0, k] * a[k, k:])) / a[k, k]

your right hand side is an array and left hand side is a single element of an array. You are trying to assign an array to a single element which throws the error. Either change left hand side to be an array too, or change right hand side to be an element instead of an array.

Upvotes: 1

Related Questions