Info

This question is closed. Reopen it to edit or answer.

How can i save all the numbers in an array, generated by an equation inside nested for loop ?

1 view (last 30 days)
I ve got this nested for loops.. xp1 and yp1 are 500 numbers each.. i am trying to find distance between those points. How can i save all the numbers that a generates in an array..?
for i = 1:1:numel(xP1)
for j = 1:1:numel(yP1)
if(i ~= 500 && j ~= 500)
a = sqrt((xP1(i) - xP1(i + 1))^2 + ((yP1(j) - yP1(j + 1))^2));

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 4 Mar 2013
Edited: Azzi Abdelmalek on 4 Mar 2013
k=0
for i = 1:1:numel(xP1)
for j = 1:1:numel(yP1)
if(i ~= 500 && j ~= 500)
k=k+1
a(k) = sqrt((xP1(i) - xP1(i + 1))^2 + ((yP1(j) - yP1(j + 1))^2));
  2 Comments
Antonio
Antonio on 4 Mar 2013
Thanks for your answer ... i would like to ask an other question that i just found out... the last element which is the 500th number has to be deducted from 1st element of the array... How can i do that? Thanks in advance...

Walter Roberson
Walter Roberson on 4 Mar 2013
a(i,j) = sqrt((xP1(i) - xP1(i + 1))^2 + ((yP1(j) - yP1(j + 1))^2));
Or, more efficiently:
xd = diff(xP1) .^ 2 ;
yd = diff(xP2) .^ 2;
a = sqrt(bsxfun(@plus, xd, yd));
  1 Comment
Walter Roberson
Walter Roberson on 4 Mar 2013
To handle combining the 500'th and the 1st, the efficient form would be
xd = diff(xP1([1:end 1]));
yd = diff(yP1([1:end 1]));
a = sqrt(bsxfun(@plus, xd, yd));

Community Treasure Hunt

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

Start Hunting!