I have a matrix of numbers (Nx,Ny) and I would like to select from that matrix a mathematical shape coordinates/components as it could be a line with a given slope.
I learned how to create a mask and how to do it in a random way but I cannot think of how to generate a mathematical-shape mask in python.
This is some of the code that I've been able to develop. If you know a better way to do this I will be also grateful of being told.
import random
import numpy as np
threshold = 0.85
radius=40
sq7=1/(radius*radius)
matrix=np.zeros((Nx,Ny))
for i in range(0,Nx):
for j in range(0,Ny):
if ((i-Nx*0.5)*(i-Nx*0.5)*sq7+(j-Ny*0.5)*(j-Ny*0.5)*sq7<=1.0):
matrix[i,j]= 1.0 - 0.1*random.random();
else:
matrix[i,j]=-1.0 + random.random();
randoms = np.random.normal(0,scale=0.002, size=matrix[mask].shape)
mask = matrix**2 < threshold
matrix[mask] += randoms * (1 - matrix[mask]**2)
At the end I found a very easy way of doing so. What I just did was to create a new matrix of the same dimensions as the one that I want to mask and then just by going through the matrix itself and comparing with the values of my function I could do it so easily. I will leave the code here.
def func_normaldist(x,Ny):
y = np.exp(-0.5*(x-int(Ny/2))**2)/np.sqrt(np.pi*2.)
return y
def mask_uvalues_centered_geometry(Nx, Ny): #u
mask = np.zeros((Nx,Ny))
# Initial configuration: rectangle of Nx x Ny
for j in range(0,Ny):
for i in range(0,Nx):
if (i < Ny*Nx*func_normaldist(j,Ny)):# and (i > int(Nx/2 + 1)):
mask[j,i] = True
else:
mask[j,i] = False;
return mask
Nx = 50
Ny = 50
a = mask_uvalues_centered_geometry(Nx,Ny)
print(a)