2

I have multiple matrices and I want to create another one 'g' based on the previous matrices that I have created. I have a general formula to generate my 'g' matrix, however, I want to change some of them based on my matrix 'theta'. If an element in 'theta' has zero value, I want to get the location of that element and find the element with the same location in 'g' to apply a second formula.

Currently, I have this code below. But the problem is that it runs quite slow. I have to generate multiple matrices similar to this and I wonder if anybody knows a faster way of doing this? Thank you in advance!

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

x = np.linspace(-100.0, 100.0, 401)

y = np.linspace(100.0, -100.0, 401)
xx, yy = np.meshgrid(x, y)

xxx = xx / 10
yyy = yy / 10

r = np.sqrt((xxx ** 2.0) + (yyy ** 2.0))

theta = np.degrees(np.arctan(xxx / yyy))

m = 1.5

uv = (xxx * xxx) + ((yyy - (m / 2)) * (yyy + (m / 2)))
umag = np.sqrt((xxx ** 2) + ((yyy - (m / 2)) ** 2))
vmag = np.sqrt((xxx ** 2) + ((yyy + (m / 2)) ** 2))

theta2 = np.arccos(uv / (umag * vmag))
g = np.absolute(theta2 * 1000 / (m * xxx))

l = len(g)

for a in range(l):
    for b in range(len(g[a])):
         if (theta[a][b] == 0):
             g[a][b] = 1 * 1000 / ((r[a][b]**2) - ((m**2) / 4))
             print(g)
         else:
             pass
arjay03
  • 23
  • 2

2 Answers2

0

You can use np.where(theta == 0). It returns tuple.

>>> a
array([[1, 2],
       [2, 3],
       [5, 6]])
>>> np.where(a==2)
(array([0, 1]), array([1, 0]))

Check this for more details

0

Ok that worked out pretty well. I changed my for loop to this one:

 row, col = np.where(theta == 0)

 for elements in g[row,col]:
     g[row,col] = 1 * 1000 / ((r[row,col]**2) - ((m**2) / 4))

It runs so much faster now that inspection of all elements was eliminated. The code now only checks where the condition is met. Thank you very much!!

arjay03
  • 23
  • 2