Search code examples
pythonperformancetime-complexitybig-onested-loops

Rewriting this nested for loop for better time complexity


I am trying to optimize the following nested for loops for a smaller amount of iterations. I feel it is very inefficient as it stands and want to think there is a better way of doing this that takes less iterations.

We have vectors M and N

  M = 1:74
  N = 1:150

  for n = 1:150
      for m = 1:74
          matrix(m,n) = m/n

If I am not mistaken this nested for loop has a time complexity of m*n being 74x150 = 11,100. I know there has to be a better way of populating the matrix(m,n) but can't think of a way of actually doing so. Help would be greatly appreciated. Thank you!

I have tried thinking about levering vectorization and reducing the time complexity to something like (m+n) vs the current (m*n) but don't know how that looks like in practice. I wouldn't wanna go into a rabbit hole before asking


Solution

  • Did you try using meshgrid approach? While actually the time complexity for meshgrid formation will be m*n but later on you can use vectorization to improve performance. The element-wise division is where the vectorization really shines, as it is much more efficient than explicitly looping over each element.

    M = np.arange(1, 75)
    N = np.arange(1, 151)
    
    
    MMESH, NMESH = np.meshgrid(M, N)
    
    matrix = MMESH / NMESH
    
    matrix_list = matrix.tolist()
    

    I dont think the time complexity can be reduced below m*n.