
How to make a nested FOR loop of distance between points?
    16 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Nicole Konforti
 el 22 de Mzo. de 2017
  
    
    
    
    
    Comentada: Iddo Weiner
      
 el 22 de Mzo. de 2017
            I have two sets each with ten objects with coordinates (x,y,z) in each set. I want to map the distances between each of the points in set 1 to each of the points in set 2. At the end, I want an array 1x100, with the 100 unique distances between each ten points of set 1 and each ten points of set 2.
To do this, I was thinking of having a code similar to this:
for I = 1:1 xvalue1 = rand(10,1)*1000; end
for J = 1:1 yvalue1 = rand(10,1)*1000; end
for K = 1:1 zvalue1 = rand(10,1)*1000; end
set1 = [xvalue1 yvalue1 zvalue1];
for I = 1:1 xvalue2 = rand(10,1)*1000; end
for J = 1:1 yvalue2 = rand(10,1)*1000; end
for K = 1:1 zvalue2 = rand(10,1)*1000; end
set2 = [xvalue2 yvalue2 zvalue2];
Which runs well. For the calculating the actual distances, my preliminary code is:
i = 1;
j = 1;
for i=1:10
    distance(i) = sqrt((xvalue2(i+1) - xvalue1(i+1)).^2 + (yvalue2(i+1) - yvalue1(i+1)).^2 + (zvalue2(i+1) - zvalue1(i+1)).^2);
    for j=1:10
        distance(j) = sqrt((xvalue2(j+1) - xvalue1(j+1)).^2 + (yvalue2(j+1) - yvalue1(j+1)).^2 + (zvalue2(j+1) - zvalue1(j+1)).^2);
    end
end
However, the error I get is that "the index exceeds matrix dimensions" Does anyone understand where my error is?
Thank you
0 comentarios
Respuesta aceptada
  Iddo Weiner
      
 el 22 de Mzo. de 2017
        Hi, you had some unnecessary bits of code there that made it complicated to follow. Here's a shorter code that does what you asked for:
% get random data
set1 = rand(10,3)*1000 ;
set2 = rand(10,3)*1000 ;
% calculate
OUT = nan(10,10); %create array for holding output
for i = 1:(length(set1))
    for j = 1:length(set2)
        OUT(i,j) = sum( (set1(i,:) - set2(j,:)).^2);
    end
end
% plot
imagesc(OUT)
ylabel('set1')
xlabel('set2')
HC = colorbar;
ylabel(HC,'distance')

1 comentario
  Iddo Weiner
      
 el 22 de Mzo. de 2017
				BTW - your error is a result using i+1. i runs until 10, so in the last iteration your i equals 11, which doesn't exist in the sets
Más respuestas (0)
Ver también
Categorías
				Más información sobre Scatter Plots en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

