title: Fitting a 3D array of data to a 1D function with numpy or scipy
body: <p>4I am currently trying to fit a lot of data to a sine function. In the case where I only have one set of data (1D array), <code>scipy.optimize.curve_fit()</code> works fine. However it does not permit a higher dimensional data input if the function itself is only one dimensional as far as i can see. I don't want to iterate over the array using for loops as that works incredibly slow in python.</p>
  
  <p>My code so far should look similar to this:</p>
  
  <pre><code>from scipy import optimize
  import numpy as np    
  def f(x,p1,p2,p3,p4): return p1 + p2*np.sin(2*np.pi*p3*x + p4)      #fit function
  
  def fit(data,guess):
     n = data.shape[0] 
     leng = np.arange(n)
     param, pcov = optimize.curve_fit(f,leng,data,guess)
     return param, pcov
  </code></pre>
  
  <p>where data is a threedimensional array (<code>shape=(x,y,z)</code>) and I would like to fit each line <code>data[:,a,b]</code> to the function with <code>param</code> being a <code>(4,y,z)</code> shaped array as output. 
  Of course, for multidimensional data this results in a</p>
  
  <p><code>ValueError: operands could not be broadcast together with shapes (2100,2100) (5)</code></p>
  
  <p>Maybe there is an easy solution to this but I am not sure how to do it. Any suggestions?</p>
  
  <p>Searching for an answer to my question proofed quite difficult since most topics with those keywords relate to the fitting of higher dimensional functions.</p>