필터 지우기
필터 지우기

How to make a nested FOR loop of distance between points?

조회 수: 1 (최근 30일)
Nicole Konforti
Nicole Konforti 2017년 3월 22일
댓글: Iddo Weiner 2017년 3월 22일
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

채택된 답변

Iddo Weiner
Iddo Weiner 2017년 3월 22일
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
Iddo Weiner
Iddo Weiner 2017년 3월 22일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by