title: model fitting with MATLAB
body: <p>I have a set of measures of signal received power  (p) at a given distance (d) and a model with unknown coefficients n1 and n2. What I have to do is find the values of n1 and n2 which minimizes the RMS error. I've seen solutions using lsqnonlin but not for piecewise defined functions. I'm a real noob in matlab and I'm having lots of trouble, please help!</p>
  <p>The given model is:<br />
  <a href="https://i.stack.imgur.com/xDMnU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDMnU.png" alt="model" /></a></p>
  <p>So far I've defined a model.m script which defines the equation above:</p>
  <pre><code>function y = modelo(d,ht,hr,h0,f,data)
  y=NaN(size(d));
  c=3*10^8;
  lambda=c/f;
  rbp = 4*(ht-h0)*(hr-h0)/lambda
  if d &lt;= rbp
      y = 20*log10(4*pi/lambda)+10*@(x)x(1)*log10(d)-data;
  else
      y =20*log10(4*pi/lambda)+10*@(x)x(1)*log10(d) + 10*@(x)x(2)*log10(d)-data;
  end
  </code></pre>
  <p>The d parameter is the distances vector and data is the measured power at that distance. All other parameters are fixed numbers.</p>
  <p>Then I'm trying to use lsqnonlin but it's not working. Any ideas on how to solve this?</p>