Reputation: 123
I am trying to solve the following question:
Consider the n simultaneous equations Ax=b, where
A_(ij) = (i+j)^2 and b_i = sum(A_ij) from j=0 to n, with i=0,1,...,n, j=0,1,...,n.
Write an program that solves these equations for any given n.
So I am supposed to create the matrix A and the vector b, and then use these to solve Ax=b. I am fine with creating A, and it is done using the following code:
A = numpy.zeros(n*n).reshape(n,n)
def matrix(n):
for i in range(0,n):
for j in range(0,n):
A[i,j] = (i+j)**2
matrix(n)
print A
For any chosen n, this gives me a nice looking nxn matrix. However, I am now struggling to create the vector b. This is my code so far:
b = numpy.zeros(n*1).reshape(n,1)
def sumRow(n):
while i = 0:
for j in range(0,n):
b[i] = math.fsum(A[i,j])
sumRow(n)
print b
First things first, I don't know how to then do it from i=0 up to i=n.
I am also getting errors when running this code which I am struggling to solve.
My thought process is as follows:
Can someone help me to modify this second block of code in order to obtain a matrix b for a given n.
Upvotes: 1
Views: 57
Reputation: 1909
This should solve your problem of populating vector b
-
b = numpy.zeros(n*1).reshape(n,1)
def sumRow(n):
for i in range(0,n):
b[i] = math.fsum(A[i]) //calculates the sum of all elements of the given row
sumRow(n)
print b
Upvotes: 1
Reputation: 2389
Here's how you can get b
using list comprehension
b = [sum(x) for x in A]
Upvotes: 1