Search code examples
matlabimage-processingalgebraeuclidean-distance

MATLAB Computing distance from a point to a set of points


Consider a matrix A:

A = magic(5)

17    24     1     8    15
23     5     7    14    16
 4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

I have to compute the following formula: w_ij = ||I(i) - I(j)|| ^ 2 from point A(1,1) to its neighborhood i.e. A(1:2, 1:2). Now I don't understand well what this formula stand for since it is not specified. Is this the Euclidean distance?

I tried

norm(A(1, 1) - A(1:2, 1:2))

But that gives me a scalar. I'm expecting a vector of 4 elements. Can you help me?


Solution

  • You can see that formula in context on page 4 of http://www.cs.berkeley.edu/~malik/papers/SM-ncut.pdf (equation 11). In that paper they use F for intensity where I assume you have I. Since your intensities are scalars, you just want to take the square of their differences.

    You want to calculate a weight matrix that calculates the affinity of any entry in A to any other entry in A. Because your A has 25 entries, your weight matrix will be 25x25.

    Since you are only worried about the brightness this is easy:

    len = length(A(:));
    W = zeros(len);
    for i = 1:len
        for j = 1:len
           W(i,j) = (A(i) - A(j))^2;
        end
    end
    

    Now if you want to look up the weight between A(1,1) and A(1,2) you can do it like this:

    i = sub2ind(size(A), 1, 1)
    j = sub2ind(size(A), 1, 2)
    W(i, j)
    

    But if you set r=1 (according to the NCuts formula) then you might want something like this:

    sigma= 10;
    r = 1;
    A = magic(3);
    siz = size(A);
    len = length(A(:));
    W = zeros(len);
    for i = 1:len
        for j = 1:len
           [xi,yi] = ind2sub(siz,i);
           [xj,yj] = ind2sub(siz,j);
           if((xi-xj)^2 + (yi-yj)^2) > r^2
               W(i,j) = 0;
           else
               W(i,j) = exp(-(A(i) - A(j))^2 / sigma^2);
           end
        end
    end
    
    A11 = sub2ind(siz, 1, 1)
    A12 = sub2ind(siz, 1, 2)
    W(A11, A12)