ODP
ODP

Reputation: 123

Where is my code going wrong in creating this matrix?

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:

  1. I create an nx1 vector of zeros.
  2. I then define a function in n which I name sumRow.
  3. Then I tell the function to do what the formula for b says.
  4. For row zero and for j in the range zero to n, I tell the computer to make the ith row of b the sum of all of the numbers in the ith row of A.

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

Answers (2)

Swastik Padhi
Swastik Padhi

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

jayant
jayant

Reputation: 2389

Here's how you can get b using list comprehension

b = [sum(x) for x in A]

Upvotes: 1

Related Questions