I'm trying to figure out how to make this switch between -1 and 1. If I set p to -1, I still get it alternating between 0 and 1.
The actual question is as follows:
Have a for loop flip the value of p between -1 and 1, changing it once each loop iteration USING A SINGLE LINE OF CODE. Display the value of p each iteration by omission of semicolon. Use the pause() function to stop the loop temporarily each iteration.
clc;
clear;
p = -1;
for k = 1 : 10
p = ~p
pause(1);
end
Any suggestions would be greatly appreciated!

 채택된 답변

Star Strider
Star Strider 2016년 10월 4일

1 개 추천

Try this:
d = -1;
for k = 1 : 10
p = d^k
pause(1);
end
or you could simplify it further as:
for k = 1 : 10
p = (-1)^k
pause(1);
end

댓글 수: 2

It worked! Thank you!
My pleasure!
If my Answer solved your problem, please Accept it.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2016년 10월 4일

댓글:

2016년 10월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by