title: Matlab Covariance Matrix Computation for Different Classes
body: <p>I've got 2 different files, one of them is an input matrix (X) which has 3823*63 elements (3823 input and 63 features), the other one is a class vector (R) which has 3823*1 elements; those elements have values from 0 to 9 (there are 10 classes).</p>
  
  <p>I have to compute covariance matrices for every classes. So far, i could only compute mean vectors for every classes with so many nested loops. However, it leads me to brain dead.</p>
  
  <p>Is there any other easy way?</p>
  
  <hr>
  
  <p>There is the code for my purpose (thanks to Sam Roberts):</p>
  
  <pre><code>xTra = importdata('optdigits.tra');
  xTra = xTra(:,2:64); % first column's inputs are all zero
  
  rTra = importdata('optdigits.tra');
  rTra = rTra(:,65); % classes of the data
  
  c = numel(unique(rTra));
  
  for i = 1:c
      rTrai = (rTra==i-1); % Get indices of the elements from the ith class
      meanvect{i} = mean(xTra(rTrai,:)); % Calculate their mean
      covmat{i} = cov(xTra(rTrai,:)); % Calculate their covariance
  end
  </code></pre>