How to create a simliarity matrix in MATLAB?

I am working on comparing multiple images. I have these image data as column vectors of a matrix called β€œimages”. I want to appreciate the similarity of the images by first calculating their Euclidean distance. Then I want to create a matrix on which I can perform several random walks. Right now, my code is as follows:

% clear % clc % close all % % load tea.mat; images = Input.X; M = zeros(size(images, 2), size (images, 2)); for i = 1:size(images, 2) for j = 1:size(images, 2) normImageTemp = sqrt((sum((images(:, i) - images(:, j))./256).^2)); %Need to accurately select the value of gamma_i gamma_i = 1/10; M(i, j) = exp(-gamma_i.*normImageTemp); end end 

My matrix M, however, ends up having a value of 1 along its main diagonal and zeros elsewhere. I expect "large" values ​​for the first few elements of each row and "small" values ​​for elements with a column index> 4. Can someone explain what is wrong? Any advice is appreciated.

+2
source share
4 answers

Since you are trying to calculate the Euclidean distance , it looks like you have an error when your brackets are placed when calculating normImageTemp . You have the following:

 normImageTemp = sqrt((sum((...)./256).^2)); %# ^--- Note that this parenthesis... 

But you really want to do this:

 normImageTemp = sqrt(sum(((...)./256).^2)); %# ^--- ...should be here 

In other words, you need to do basic squaring, then summation, then the square root. What you are doing now is summing the elements first, then squaring and taking the square root of the summation, which essentially cancel each other out (or are actually equivalent only to taking an absolute value).

By the way, you really can use the NORM function to perform this operation, for example:

 normImageTemp = norm((images(:, i) - images(:, j))./256); 
+2
source

The results you get look reasonable. Recall the behavior of exp (-x). When x is zero, exp (-x) is 1. When x is large, exp (-x) is zero.

Perhaps if you do M (i, j) = normImageTemp; you will see what you expect to see.

0
source

Consider this solution:

 I = Input.X; D = squareform( pdist(I') ); %'# euclidean distance between columns of I M = exp(-(1/10) * D); %# similarity matrix between columns of I 

PDIST and SQUAREFORM are functions from the statistics toolbar.

Otherwise, consider this equivalent vector code (using only the built-in functions):

 %# we know that: ||uv||^2 = ||u||^2 + ||v||^2 - 2*uv X = sum(I.^2,1); D = real( sqrt(bsxfun(@plus,X,X')-2*(I'*I)) ); M = exp(-(1/10) * D); 

As explained in other answers, D is the distance matrix, and exp(-D) is the similarity matrix (which is why you get it diagonally)

0
source

there is already a implemented pdist function, if you have matrix A, you can directly do

Sim = squareform (pdist (A))

0
source

Source: https://habr.com/ru/post/975411/


All Articles