while trying to program something I've come to need to create a 2D array(matrix) from a function that takes matrix indices (i and j in below example) as arguments and returns the matrix element.
I've seen from other answers that numpy.fromfunction() along with numpy.vectorize() should do the trick, however in my case those two seem to give a different result, what could be wrong?
More specifically I am comparing this:
for i in range(velikost):
for j in range(velikost):
u[i][j] = pomozna(i,j)
return u
to this(which I thought is equivalent to the above):
return np.fromfunction(np.vectorize(pomozna),u.shape)
Below is my full code, if you wish to run it by yourself. Any help appreciated, thanks!
import numpy as np
def jacobi(u,h,q):
velikost = u[0].size
star = np.copy(u)
def pomozna(i,j):
if i==0 or i==velikost-1 or j==0 or j==velikost-1:
return 0
return 1/4*(star[int(i+1)][int(j)]+star[int(i-1)][int(j)]+star[int(i)][int(j+1)]+star[int(i)][int(j-1)] - h*h*q[int(i)][int(j)])
#return np.fromfunction(np.vectorize(pomozna),u.shape)
for i in range(velikost):
for j in range(velikost):
u[i][j] = pomozna(i,j)
return u
h=0.05
iksi = np.linspace(0,1,int(1/h))
ipsiloni = np.linspace(0,1,int(1/h))
qji = [[-1 for iks in iksi] for ips in ipsiloni]
zacetna = np.asarray([[1.0 for iks in iksi] for ips in ipsiloni])
zacetna[0] = np.zeros(iksi.size)
zacetna[-1]=np.zeros(iksi.size)
zacetna[:,0] = np.zeros(iksi.size)
zacetna[:,-1] = np.zeros(iksi.size)
print(jacobi(zacetna,h,qji))