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)
Show older comments
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));
0 Comments
Answers (2)
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
Azzi Abdelmalek
on 4 Mar 2013
If you mean how to find a(500) from a(1), this is not obvious, I don't see
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
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));
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!