필터 지우기
필터 지우기

How can I convert this for if loop into a while loop?

조회 수: 1 (최근 30일)
Jordan Means
Jordan Means 2018년 9월 11일
댓글: Jordan Means 2018년 9월 11일
Hello. MATLAB beginner here. I'm trying to convert a for loop to a while loop to finish up a final homework problem and it's supposed to get the same results, but it's not. I'm only getting the random numbers from the beginning equation. I believe the issue shouldn't be this hard to find, but I can't pinpoint what's wrong.
x=6*rand(1,10)+2
for i=1:10
if i<5
x(i)=-1;
elseif i>=5 && i<8
x(i)=1;
else
x(i)=3;
end
end
x
  댓글 수: 1
Stephen23
Stephen23 2018년 9월 11일
@Jordan Means: please show us the while loop that you tried.

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

채택된 답변

Steven Beumer
Steven Beumer 2018년 9월 11일
x=6*rand(1,10)+2
i = 1;
while i<11
if i<5
x(i)=-1;
elseif i>=5 && i<8
x(i)=1;
else
x(i)=3;
end
i = i+1;
end
x
Should do the trick, just don't forget to update you i .
  댓글 수: 1
Jordan Means
Jordan Means 2018년 9월 11일
Thanks. I guess the i = i + 1 was what I was missing.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by