title: What is the fastest way to calculate a matrix product of vectors built element-wise?
body: <p>I have the following MATLAB code to calculate the strain energy. I want to optimize this code, because this is where most of my time in an optimization problem is spent.</p>
  <pre><code> stiffness = [6 x 6 matrix] % For a MWE, try magic(6)+magic(6)';
   exx(:)=[100 x 100 matrix]; eyy(:)=[100 x 100 matrix]; %etc.
  
   for idr = 1:length(r) % Index of r-location
       for idt = 1:length(theta) % Index of theta location
           e = [exx(idr,idt);eyy(idr,idt);ezz(idr,idt);2*exz(idr,idt);2*eyz(idr,idt);2*exy(idr,idt)]; % strain vector
           E(idr,idt) = e'*stiffness*e; %$ Strain energy at this location
       end
   end
  </code></pre>
  <p>There are two problems here:</p>
  <ul>
  <li>Since <code>length(r)==length(theta)==100</code>, this piece of code gets called 10k times.</li>
  <li>About a third of the time spent in the loop is on assembling <code>e</code> without actually doing any calculation.</li>
  </ul>
  <p>I think there should be some ways to speed this up significantly by properly using vectorization, but I'm not entirely sure how to proceed in this particular case.</p>
  <p>Note: there are some similar questions, e.g. <a href="https://stackoverflow.com/questions/69124927/what-is-the-fastest-way-to-vectorize-a-large-number-of-matrix-operations-in-nu">this</a>, so perhaps there are some ideas that can be translated to MATLAB.</p>