필터 지우기
필터 지우기

How do i convert this for loop into a while loop?

조회 수: 1 (최근 30일)
Ilker Enes Çirkin
Ilker Enes Çirkin 2019년 5월 28일
댓글: Ilker Enes Çirkin 2019년 5월 28일
I just couldn't figure out how to convert it into a while loop. here is the code:
clc;
clear;
clear all;
n=input('Enter the number of elements in your array:'); % number of array elements
for i=1:n
values(i)=input('Enter the values:')
if values(i)<0
values(i)=values(i)*(-1)
end
end
for k=1:(n-1)
d=k+1
Xaverage(k)=(values(d)+values(k))/2
end
y=1:1:n;
plot(values,y)
hold on
z=1:1:(n-1);
plot(Xaverage,z)
  댓글 수: 1
Ilker Enes Çirkin
Ilker Enes Çirkin 2019년 5월 28일
this is what i have tried so far:
clc;
clear;
clear all;
n=input('Enter the number of elements in your array:'); % number of array elements
i=1;
while i<n
values(i)=input('Enter the values:');
if values(i)<0
values(i)=values(i)*(-1)
end
end
k=1;
while k<(n-1)
d=k+1
Xaverage(k)=(values(d)+values(k))/2
end
y=1:1:n;
plot(values,y)
hold on
z=1:1:(n-1);
plot(Xaverage,z)

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

채택된 답변

James Tursa
James Tursa 2019년 5월 28일
This for loop:
for i=1:n
% stuff
end
is equivalent to this while loop:
i = 1;
while i <= n
% stuff
i = i + 1;
end
Your biggest problem is you never increment i or k in your while loops.
  댓글 수: 2
Ilker Enes Çirkin
Ilker Enes Çirkin 2019년 5월 28일
yes ı noticed that after i shared this but after changing it i get the error saying Index exceeds the number of array elements (2).
James Tursa
James Tursa 2019년 5월 28일
Please post your current code.

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

추가 답변 (1개)

Ilker Enes Çirkin
Ilker Enes Çirkin 2019년 5월 28일
This is my current code:
n=input('Enter the number of elements in your array:'); % number of array elements
i=1;
while i<=n
i=i+1;
values(i)=input('Enter the values:')
if values(i)<0
values(i)=values(i)*(-1)
end
end
k=1;
while k<=(n-1)
k=k+1;
d=k+1
Xaverage(k)=(values(d)+values(k))/2
end
y=1:1:n;
plot(values,y)
hold on
z=1:1:(n-1);
plot(Xaverage,z)
  댓글 수: 2
James Tursa
James Tursa 2019년 5월 28일
You did not copy the form of the while loop correctly. Incrementing the index variable is the LAST thing you do in the loop as I have written it. So your i=i+1 and k=k+1 lines need to be the LAST things you do in the loop, not the first.
Ilker Enes Çirkin
Ilker Enes Çirkin 2019년 5월 28일
oh thank you so much it works now :)

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

카테고리

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

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by