title: Efficient way to compute multiple euclidean distances Matlab
body: <p>I am training my own self organizing map to cluster colorvalues. Now I want to make some sort of a <a href="http://ars.els-cdn.com/content/image/1-s2.0-S0925231208004475-gr11.jpg" rel="nofollow">U-matrix</a> to show euclidean distances between the nodes and their direct neighbors. My problem now is, that my algorithm is quite unefficient!! There is certainly a way to compute this more efficiently?</p>
  
  <pre><code>function displayUmatrix(dims,weights) %#dims is [30 30], size(weights) = [900 3], 
                                        %#consisting of values between 1 and 0
  
  hold on; 
  axis off;
  A = zeros(dims(1), dims(2), 3);
  B = reshape(weights',[dims(1) dims(2) size(weights,1)]);
  if size(weights,1)==3
      for i=1:dims(1)
          for j=1:dims(2)
              if i~=1
                  if j~=1
                      A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j-1,:)).^2;
                  end
                  A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j,:)).^2;
                  if j~=dims(2)
                      A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j+1,:)).^2;
                  end
              end
              if i~=dims(1)
                  if j~=1
                      A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j-1,:)).^2;
                  end
                  A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j,:)).^2;
                  if j~=dims(2)
                      A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j+1,:)).^2;
                  end
              end 
              if j~=1
                  A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i,j-1,:)).^2;
              end
              if j~=dims(2)
                  A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i,j+1,:)).^2;
              end
              C(i,j)=sum(A(i,j,:));
          end
      end
      D = flipud(C);
      maximum = max(max(D));
      D = D./maximum;
      imagesc(D)
  else
      error('display function does only work on 3D input');
  end
  hold off;
  drawnow;
  </code></pre>
  
  <p>end</p>
  
  <p>Thanks, Max</p>