Flipping between two values using a for loop

10 Ansichten (letzte 30 Tage)
Michael Doherty
Michael Doherty am 4 Okt. 2016
Kommentiert: Star Strider am 5 Okt. 2016
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!

Akzeptierte Antwort

Star Strider
Star Strider am 4 Okt. 2016
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 Kommentare
Michael Doherty
Michael Doherty am 4 Okt. 2016
It worked! Thank you!
Star Strider
Star Strider am 5 Okt. 2016
My pleasure!
If my Answer solved your problem, please Accept it.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by