How do I create a simliarity matrix in MATLAB?

时光怂恿深爱的人放手 提交于 2019-11-28 14:15:20

Since you're trying to compute a Euclidean distance, it looks like you have an error in where your parentheses are placed when you compute normImageTemp. You have this:

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

But you actually want to do this:

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

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

Incidentally, you can actually use the function NORM to perform this operation for you, like so:

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

The results you're getting seem reasonable. Recall the behavior of the exp(-x). When x is zero, exp(-x) is 1. When x is large exp(-x) is zero.

Perhaps if you make M(i,j) = normImageTemp; you'd see what you expect to see.

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 Toolbox.

Otherwise consider this equivalent vectorized code (using only built-in functions):

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

As was explained in the other answers, D is the distance matrix, while exp(-D) is the similarity matrix (which is why you get ones on the diagonal)

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

Sim= squareform(pdist(A))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!