How to create for loop for calculating euclidean distance of a matrix?
Show older comments
Hi!
I am having some trouble figuring out how to structure this for loop.. I have an array called 'Coordinates' that contains a varying number of rows, and constant number of columns. col 1 = x, col 2 = y, col 3 = z. The number of rows varies based on how many events occur in a single observation, but columns are consistent throughout.
Coordinates =
-.6 .5 -4.1
-.9 .4 -4.1
-1.1 .2 -4.2
I need to write a for loop that calculates the euclidean distance between each of these xyz coordinates and store it in a new array called 'Distances'.
icoordinates = nobservations - 1; %creates a variable that consists of number of observations -1
config.Calculated.Distances = []; % create empty vector to store distances
for i_coord = 1:icoordinates %for each observation
curdistance = config.Calculated.Coordinates(:, :, i_coord);
curdistance = sqrt(sum((Coordinates(i+1,:) - Coordinates(i,:)).^2));
config.Calculated.Distances = [config.Calculated.Distances curdistance];
end
close all;
When I run the code as above ^ I get the following error and my Distances array remains empty
1 icoordinates = nobservations - 1; % creates a variable that consists of number of scan patterns -1
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in distancecalc (line 7)
curdistance = sqrt(sum((Coordinates(i+1,:) - Coordinates(i,:)).^2));
Any help with figuring out how to structure this for loop would be greatly appreciated, I'm a MATLAB novice and would love to learn!
Thanks,
Jade
Accepted Answer
More Answers (1)
James Tursa
on 3 Apr 2024
0 votes
Does pdist() do what you want:
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!