For loop code not working right?

조회 수: 4 (최근 30일)
Bob
Bob 2015년 2월 9일
댓글: James Tursa 2015년 2월 9일
Question: Set the variable p9 to equal 7. Then run a for loop which goes through the numbers n = 0, 3, 6, 9, ..., 300 and adds them each in turn to p9 (changing it each time).
Code:
p9=7;
for p9=[0:3:300];
disp(num2str(p9));
p9=p9+n;
end;
This is giving me the wrong answer and I am not sure why? Thanks for your help!
  댓글 수: 1
Stephen23
Stephen23 2015년 2월 9일
disp works just fine on numeric data, you don't need the num2str.

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

답변 (2개)

James Tursa
James Tursa 2015년 2월 9일
You have used the variable p9 as your loop index AND as the accumulation variable. Use a different variable name for the loop index, e.g. use k=0:3:300 instead of p9=0:3:300. Then you can add k to p9 in your loop (instead of n ... where does n come from?).
  댓글 수: 8
Bob
Bob 2015년 2월 9일
My teacher said it should stop when n=300. So I think I am done?
James Tursa
James Tursa 2015년 2월 9일
If you understand the code, then I think you are done also.

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


Image Analyst
Image Analyst 2015년 2월 9일
In a for loop, if you change the loop iterator variable, your "p9", inside the loop, it will have that value for the remainder of that iteration of the loop. However, once it hits the end and start the next iteration of the loop, it will have the value that it would have had, had you not changed it - it will not have anything to do with what value you changed it to.

카테고리

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