1

Suppose that I have a (400,10) array called x and a (400,10) array called y. Is that possible to do a polyfit of each row in y to the corresponding row in x without iteration? If with for loop it will be something like

import numpy as np

coe = np.zeros((400,3))    
for i in np.arange(y.shape[0]): 
    coe[i,:] = np.polyfit(x[i,:], y[i,:], 2) 

Because the 400 rows in x is totally different, I cannot just apply np.polyfit with the same x coordinate to a multi-dimensional array y.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
lelouchkako
  • 123
  • 1
  • 7

1 Answers1

0

Have you tried a comprehension?

coe = [tuple(np.polyfit(x[i,:], y[i,:], 2)) for i in range(400)]

  • The range(400) emits the values 0 to 399 into i
  • For each i, you compute the polyfit for x[i,:] vs y[i,:]. I believe the results are a tuple (p, v)
  • The resulting list-of-tuples is assigned to coe

At the innermost levels, this is an iteration - but in Python 3, such comprehensions are optimized for performance at the C level, so you will probably see a nice performance boost doing it this way over using a for: loop.

matthew.peters
  • 571
  • 4
  • 6