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

32 ビュー (過去 30 日間)
Samantha Horton
Samantha Horton 2017 年 12 月 9 日
編集済み: Bill Tubbs 2022 年 10 月 31 日
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"

回答 (4 件)

Andrei Bobrov
Andrei Bobrov 2017 年 12 月 9 日
out = 2*rem(1:12,2) - 1

Star Strider
Star Strider 2017 年 12 月 9 日
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 件のコメント
Stephen23
Stephen23 2017 年 12 月 9 日
Why so complex?:
>> (-1).^(0:11)
ans =
1 -1 1 -1 1 -1 1 -1 1 -1 1 -1
Zachery Vrbas
Zachery Vrbas 2022 年 10 月 29 日
It was so obvious.
Thank you, good sir

サインインしてコメントする。


Bill Tubbs
Bill Tubbs 2022 年 10 月 31 日
Even easier:
out = cumprod(-ones(1, 12))
out =
-1 1 -1 1 -1 1 -1 1 -1 1 -1 1
  2 件のコメント
DGM
DGM 2022 年 10 月 31 日
編集済み: DGM 2022 年 10 月 31 日
That's faster than I expected, but I guess it makes some sense.
N = 1E6;
timeit(@() f1(N))
ans = 0.0230
timeit(@() f2(N))
ans = 0.0240
timeit(@() f3(N))
ans = 0.0231
timeit(@() f4(N))
ans = 0.0020
timeit(@() f5(N))
ans = 1.7284e-04
timeit(@() f6(N))
ans = 0.0010
function f1(N)
% slower than i expected
out = 2*rem(1:N,2) - 1;
end
function f2(N)
out = (-ones(1,N)).^(0:(N-1));
end
function f3(N)
out = (-1).^(0:(N-1));
end
function f4(N)
% faster than i expected
out = -cumprod(-ones(1,N));
end
function f5(N)
% only works if N is even!
out = reshape(repmat([1;-1],[1 N/2]),1,[]);
end
function f6(N)
% this is a bit slower and uglier than f5, but works for any N
out = reshape(repmat([1;-1],[1 ceil(N/2)]),1,[]);
out = out(1:N);
end
Bill Tubbs
Bill Tubbs 2022 年 10 月 31 日
Nice! Thanks for pointing out the simplification (f3). I will update my comment.

サインインしてコメントする。


Bill Tubbs
Bill Tubbs 2022 年 10 月 31 日
編集済み: Bill Tubbs 2022 年 10 月 31 日
Here's another way. A geometric series:
out = (-1).^(0:11)
out =
1 -1 1 -1 1 -1 1 -1 1 -1 1 -1

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by