title: Matlab Fill previous value if missing value (or zero)
body: <p>I have a vector containing a time series with different values and some missing values inbetween that are set to zero:</p>
  
  <pre><code>X=[0,0,2,0,5,0,0,0,4,0];
  </code></pre>
  
  <p>I want to create a new vector where the missing values (zeros) are populated by the previous value if one exist so that I get a new vector looking like:</p>
  
  <pre><code>Z=[0,0,2,2,5,5,5,5,4,4];
  </code></pre>
  
  <p>I have been browsing through the Matlab help and forums like this to find a neat and suitable function that would solve this for me with a one line solution or similar, but I have failed to do so. I can solve the problem through a few different steps according to below but I am guessing that there must be a better and easier solution available?</p>
  
  <p>Current solution:</p>
  
  <pre><code>X=[0,0,2,0,5,0,0,0,4,0];
  ix=logical(X);
  Y = X(ix);
  ixc=cumsum(ix);
  Z=[zeros(1,sum(~logical(ixc))) Y(ixc(logical(ixc)))];
  </code></pre>
  
  <p>This does the trick, but it seems like an overly complicated solution to a simple problem, so can anyone help me with a better one? Thanks.</p>