title: Kalman Filter implementation for one dimensional vector
body: <p>I am having an hard time figuring out something really stupid I think. </p>
  
  <p>I want to refresh my kalman filter knowledge but I am not able to make it work. </p>
  
  <p>In a simple case with 
  real states x:</p>
  
  <pre><code>x = [   1000    750 563 422 316 237 178 133 100 75]';
  </code></pre>
  
  <p>and observations</p>
  
  <pre><code>z_array = [ 1056    943 469 235 433 230 116 136 -75 267]';
  </code></pre>
  
  <p>I get something really nice (<em>estimated</em> stands for FILTERED):</p>
  
  <p><a href="https://i.stack.imgur.com/rzCki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rzCki.png" alt="enter image description here"></a></p>
  
  <p>When instead I use another signal, more complex. I don't know why but it doesn't work (<em>estimated</em> stands for FILTERED). </p>
  
  <p><a href="https://i.stack.imgur.com/WduT4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WduT4.png" alt="enter image description here"></a></p>
  
  <p>The problem, I am quite sure is in how I choose the <code>a</code> and <code>r</code> in my code for the second case. But how can I change them? </p>
  
  <p>Here is the short code I have written in MATLAB and I am getting lost (I am really ashamed because I should know how to do this!!).</p>
  
  <pre><code>close all
  
  z_array = noisyMeas.signals.values;
  x = meas.signals.values;
  
  a = 0.75;
  r= 200;
  p=1;
  
  % x = [ 1000    750 563 422 316 237 178 133 100 75]';
  % z_array = [   1056    943 469 235 433 230 116 136 -75 267]';
  
  xhat_array = zeros(length(z_array),1);
  xhat = z_array(1);
  xhat_array(1) = xhat;
  
  % Core of the Kalman Filter 
  for k=2:length(x)
      z = z_array(k);
  
      % Predict
      xhat = a * xhat;
      p    = a * p * a;
  
      % Update
      g    = p  / (p  + r);
      xhat = xhat + g * (z - xhat);
      p    = (1 - g) * p;
      xhat_array(k) = xhat;
  end
  
  % plotting
  figure
  hold on
  plot(xhat_array,'r')
  plot(x,'b');
  plot(z_array,'g')
  grid on
  legend('estimated','notNoisy','Noisy')
  </code></pre>
  
  <p>Thanks in advance for your help. </p>