Search code examples
arraysmatlabmatrixvectorizationbsxfun

Find the distance from one point in a matrix to all other points in a matrix


I have a matrix a and I want to calculate the distance from one point to all other points. So really the outcome matrix should have a zero (at the point I have chosen) and should appear as some sort of circle of numbers around that specific point.

This is what I have already but I cant seem to get the correct outcome.

a = [1 2 3 4 5 6 7 8 9 10]

for i = 2:20
    a(i,:) = a(i-1,:) + 1;
end

N = 10

for I = 1:N
    for J = 1:N
        dx = a(I,1)-a(J,1);
        dy = a(I,2)-a(J,2);
        distance(I,J) = sqrt(dx^2 + dy^2)
    end
end

Solution

  • This is what i was looking for, but thanks for all the suggestions.

    A = rand(5, 5);
    select_cell = [3 3];
    distance = zeros(size(A, 1), size(A, 2));
    for i = 1:size(A, 1)
        for j = 1:size(A, 2)
            distance(i, j) = sqrt((i - select_cell(1))^2 + (j - select_cell(2))^2);
        end
    end
    disp(distance)
    

    Also you can improve it by using vectorisation:

    distances = sqrt((x-xCenter).^2+(y-yCenter).^2