title: Vectorizing for loops in MATLAB
body: <p>I'm not too sure if this is possible, but my understanding of MATLAB could certainly be better.</p>
  
  <p>I have some code I wish to vectorize as it's causing quite a bottleneck in my program. It's part of an optimisation routine which has many possible configurations of Short Term Average (STA), Long Term Average (LTA) and Sensitivity (OnSense) to run through. </p>
  
  <p>Time is in vector format, FL2onSS is the main data (an Nx1 double), FL2onSSSTA is its STA (NxSTA double), FL2onSSThresh is its Threshold value (NxLTAxOnSense double)</p>
  
  <p>The idea is to calculate a Red alarm matrix which will be 4D - the alarmStatexSTAxLTAxOnSense that is used throughout the rest of the program. </p>
  
  <pre><code>Red = zeros(length(FL2onSS), length(STA), length(LTA), length(OnSense), 'double');
  for i=1:length(STA)
      for j=1:length(LTA)
          for k=1:length(OnSense)
              Red(:,i,j,k) = calcRedAlarm(Time, FL2onSS, FL2onSSSTA(:,i), FL2onSSThresh(:,j,k));
          end
      end
  end
  </code></pre>
  
  <p>I've currently got this repeating a function in an attempt to get a bit more speed out of it, but obviously it will be better if the entire thing can be vectorised. In other words I do not need to keep the function if there is a better solution.</p>
  
  <pre><code>function [Red] = calcRedAlarm(Time, FL2onSS, FL2onSSSTA, FL2onSSThresh)
  
  % Calculate Alarms
  % Alarm triggers when STA &gt; Threshold
  
  zeroSize = length(FL2onSS);
  
  %Precompose
  Red = zeros(zeroSize, 1, 'double');
  
  for i=2:zeroSize
      %Because of time chunks being butted up against each other, alarms can
      %go off when they shouldn't. To fix this, timeDiff has been
      %calculated to check if the last date is different to the current by 5
      %seconds. If it isn't, don't generate an alarm as there is either a
      %validity or time gap.
      timeDiff = etime(Time(i,:), Time(i-1,:));
      if FL2onSSSTA(i) &gt; FL2onSSThresh(i) &amp;&amp; FL2onSSThresh(i) ~= 0 &amp;&amp; timeDiff == 5 
          %If Short Term Avg is &gt; Threshold, Trigger
          Red(i) = 1;
      elseif FL2onSSSTA(i) &lt; FL2onSSThresh(i) &amp;&amp; FL2onSSThresh(i) ~= 0 &amp;&amp; timeDiff == 5
          %If Short Term Avg is &lt; Threshold, Turn off
          Red(i) = 0;
      else
          %Otherwise keep current state
          Red(i) = Red(i-1);
      end
  end
  end
  </code></pre>
  
  <p>The code is simple enough so I won't explain it any further. If you need elucidation on what a particular line is doing, let me know.</p>