Euclidean distance between images
<p><a href="https://i.stack.imgur.com/3ToBR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3ToBR.png" alt="enter image description here"></a>I have two images, say <code>P</code> and <code>S</code>, of size 8192×200, and I want to calculate a custom "Euclidean distance" between them. Currently I use the following steps:</p>

<ol>
<li><p>Reshape the images into a pair of column and row vectors:</p>

<pre class="lang-none prettyprint-override"><code>Ip = Ip(:).';
Is = Is(:);
</code></pre></li>
<li><p>Calculate a metric matrix, <code>G</code>, whose entries are given by the formula</p>

<pre><code>G(i,j) = 1/(2*pi*r*r) * exp((-d*d)/(2*r*r));
</code></pre>

<p>where <code>r</code> is a global parameter that varies from 0 to 20, say, and <code>d</code> is the distance between pixel <code>i</code> and pixel <code>j</code>. E.g., if pixel <code>i</code> is <code>(k,l)</code> and pixel <code>j</code> is <code>(k1,l1)</code>, then <code>d = sqrt((k-k1)^2 + (l-l1)^2);</code>. Pixel 1 will be <code>(1,1)</code>, Pixel 2 will be <code>(1,2)</code>, and so on. Therefore, the size of matrix <code>G</code> will be <code>1638400×1638400</code>. </p></li>
<li><p>Compute the final (scalar) Euclidean distance between two images, using:</p>

<pre><code>ImEuDist = sqrt( (Ip-Is) * G * (Ip-Is).' );  
</code></pre></li>
</ol>

<p>I have already written some code using a mex function, but it is taking too long before giving the results (5-6 Hours) - see <a href="https://stackoverflow.com/questions/36977008/matlab-taking-too-much-time-in-computing-mex-function-for-large-array">this SO question</a> for code and more discussion on this.</p>

<p>Please help me to optimize this; I would ideally like it to run in a matter of seconds. Note that I am not interested in solutions involving the GPU. </p>