Abhi7731756
Abhi7731756

Reputation: 27

Hilbert matrix code in python

A Hilbert matrix is a matrix whose elements are given by:

aij=(i+j-1)-1

So I tried to code this in python. Here is my code:

import math

a = int(input("Enter row"))
b = int(input("Enter column"))

def hilmat(a,b):
    li=[0]*b
    for i in range(a):
        for j in range(b):
            if(i+j>0):  
                ele=math.pow((i+j-1),-1)
                li += ele

            else:
                ele=math.pow((1-i-j),-1)
                li += ele
        j=j+1
    i=i+1

    return li


hilmat(a,b)

Running this throws this error:

Float object not iterable

How do I resolve this?

Upvotes: 2

Views: 4630

Answers (3)

CFD Satish
CFD Satish

Reputation: 1

This is my first post on stackoverflow. I found above two answers quite useful.

Here is my not so efficient code but in a different way:

import numpy as np

s = 5
H = np.zeros((s, s))

for c in range(s):
    for r in range(s):
        H[c, r] = 1 / (c + r + 1)

print(H)

Upvotes: 0

Olivier Melançon
Olivier Melançon

Reputation: 22314

The operation li += ele attempts to extend the list li with the iterable ele. Here ele is not an iterable but a float, so you want to append it. Replace this line by.

li[i].append(ele)

Although, you can efficiently build this matrice with a single list-comprehension.

Code

def hilmat(a, b):
    return [[1 / (i + j + 1) for j in range(b)] for i in range(a)]

Example

from pprint import pprint

pprint(hilmat(3, 3))

Output

[[1.0, 0.5, 0.33],
 [0.5, 0.33, 0.25],
 [0.33, 0.25, 0.2]]

Upvotes: 1

Benedict Randall Shaw
Benedict Randall Shaw

Reputation: 738

The error here arises from li += ele; as li is of type list, Python takes this line as an instruction to concatenate ele onto the end of li; but ele is a float, so this cannot be done, as it is not a list, and so an error is raised.

Since you need a list of lists, you should set li initially to [[]]*b; but in fact, to give li shape [a,b], you want to set li=[[]]*a.

In ele=math.pow((i+j-1),-1), you should note that as Python indices start at 0, you may want to use ele=math.pow((i+j+1),-1) instead.

A more usual syntax to append something to an array is to use the append method.

i=i+1, j=j+1 are both redundant, as the for loop already handles increments. In fact, they may cause errors.

return li should be indented with the rest of the function.

Your final function should be:

def hilmat(a,b):
    li=[[]]*a
    for i in range(a):
        for j in range(b):
            ele=math.pow((i+j+1),-1)
            li[i].append(ele)
    return li

Upvotes: 2

Related Questions