Home > database >  Generate 2D distribution avoiding loops
Generate 2D distribution avoiding loops

Time:02-24

I want to construct a 2D Gassuian-like distribution on a (Nx, Ny) array of the form:

 return np.exp(-0.5*((x-xp)**2   (y-yp)**2)/SG**2)

where (x,y), in this case, would correspond to [i, j] matrix indices.

I am doing this by looping through a np.zeros((Nx,Ny)) matrix and updating its values with the defined function.

Basically, I would like to know if there is a way to generate a similar result but avoid the for loops that I am using here. My intuition tells me that np.meshgrid or zip(x, y) should do it but I have been unable to replicate it.

(I would like to avoid using the auxiliar distribution_Gp function and to be able to use directly normaldist function).

Here is my sample code of how I am using it all together:

import numpy as np
def normaldist(x, y, Nx, Ny, xp, yp, SG=1):
    """2D-mesh (Nx,Ny) with Gaussian distribution values."""
    z = np.exp(-0.5*((x-xp)**2   (y-yp)**2)/SG**2)
#     /(SG*np.sqrt(np.pi*2.)))  # non-normalized
    return z


def distribution_Gp(Nx, Ny, xp, yp, SG=1):
    """Fill up the C0(Nx, Ny) array for the specified values and conditions."""
    mask = np.zeros((Nx, Ny))
    for j in range(0, Ny):
        for i in range(0, Nx):
            if(i <= Nx*Ny*normaldist(i, j, Nx, Ny, xp, yp, SG)):
                mask[i, j] = normaldist(i, j, Nx, Ny, xp, yp, SG)
    return mask
Nx = 11
Ny = Nx
arr_img = distribution_Gp(Nx, Ny, Nx//2, Ny//3, SG=2)

CodePudding user response:

A matrix with values sampled from a normal distribution can be accomplished by :

np.random.normal(mean, std, (Nx, Ny))

where Nx and Ny are shapes of the output, as in your code.

If You want to apply any custom function to a matrix then this can be accomplished by:

arr = np.zeros((Nx, Ny))
f = lambda x: x   3
result = f(arr)

CodePudding user response:

By using lambda and with two arguments and meshgrid it is possible to replicate distribution_Gp.

Using lambda and avoiding using the intermediate function:

x = np.linspace(0, 10, Nx)
y = np.linspace(0, 10, Ny)
arr = np.zeros((Nx, Ny))
f = lambda x, y: normaldist(x, y, Nx//2, Ny//3, SG=2).T
X, Y = np.meshgrid(x, y)
result = f(X, Y)

which produces the same result as:

result = distribucio_de_puntsG(Nx, Ny, Nx//2, Ny//L, SG=2)
  • Related