how would i get a while loop to repeat this code 26 times?

조회 수: 1 (최근 30일)
Josh Williams
Josh Williams 2020년 3월 15일
댓글: Josh Williams 2020년 3월 15일
shiptext= [22 6;38 21;24 36;2 30;6 2;15 31;22 15;24 15;10 33;29 11;32 15;29 21;31 4;25 27;29 27;10 11;35 17;15 14;22 20;21 29;23 22;3 22;33 9;8 38;10 4;11 29]
shipnumber= size(shiptext,1)
disp(shipnumber)
plot(shiptext(:,1),shiptext(:,2),'.');
idr1=randi(26,1,1);
row1=shiptext(idr1,:);
idr2=randi(26,1,1);
row2=shiptext(idr2,:);
a=row2-row1
xdistance=a(1)
ydistance=a(2)
distance=sqrt(((xdistance)^2)+((ydistance)^2));
disp(distance)
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 3월 15일
What do you want to repeat 26 times? You can repeat a piece of code 26 times using for loop.
for i=1:26
% your code
end
Josh Williams
Josh Williams 2020년 3월 15일
I need the code to run 26 times to give me 26 answers for distance at the end (each time generating a different random matrix) however im only allowed to use while loops.

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

채택된 답변

Sriram Tadavarty
Sriram Tadavarty 2020년 3월 15일
Hi Josh,
You can do the following
i = 1; % loop index
while i <= 26
shiptext= [22 6;38 21;24 36;2 30;6 2;15 31;22 15;24 15;10 33;29 11;32 15;29 21;31 4;25 27;29 27;10 11;35 17;15 14;22 20;21 29;23 22;3 22;33 9;8 38;10 4;11 29]
shipnumber= size(shiptext,1)
disp(shipnumber)
plot(shiptext(:,1),shiptext(:,2),'.');
idr1=randi(26,1,1);
row1=shiptext(idr1,:);
idr2=randi(26,1,1);
row2=shiptext(idr2,:);
a=row2-row1
xdistance=a(1)
ydistance=a(2)
distance(i)=sqrt(((xdistance)^2)+((ydistance)^2)); % Stores distance for each loop index
%disp(distance)
i = i+1;
end
disp (distance)
This should do what you have asked for.
Regards,
Sriram

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by