# How to make an array of alternating 1 and -1?

215 views (last 30 days)
Samantha Horton on 9 Dec 2017
Edited: Bill Tubbs on 31 Oct 2022
So far I have
xc = ones(1,12) for n=0:1:11 xc(n) = (-1).^n end
Mathematically, shouldn't it come out to an array of [1,-1,1,-1,1,-1,1,-1,1,-1]? I am getting this error:
"Subscript indices must either be real positive integers or logicals.
Error in test (line 3) xc(n) = (-1).^n"

Andrei Bobrov on 9 Dec 2017
out = 2*rem(1:12,2) - 1

Star Strider on 9 Dec 2017
MATLAB indexing begins with 1, not 0, so you have to adjust your code slightly:
xc = ones(1,12);
for n=1:12
xc(n) = (-1).^(n-1);
end
xcv = (-ones(1,12)).^(0:11); % Vectorised Version
The ‘vectorised version’ is simply to demonstrate how to use MATLAB’s vectorising ability to do the same operation.
##### 2 CommentsShowHide 1 older comment
Zachery Vrbas on 29 Oct 2022
It was so obvious.
Thank you, good sir

Bill Tubbs on 31 Oct 2022
Edited: Bill Tubbs on 31 Oct 2022
Here's another way. A geometric series:
out = (-1).^(0:11)
out =
1 -1 1 -1 1 -1 1 -1 1 -1 1 -1

Bill Tubbs on 31 Oct 2022
Even easier:
out = cumprod(-ones(1, 12))
out =
-1 1 -1 1 -1 1 -1 1 -1 1 -1 1
##### 2 CommentsShowHide 1 older comment
Bill Tubbs on 31 Oct 2022
Nice! Thanks for pointing out the simplification (f3). I will update my comment.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by