Hi! I want to generate a column of 30 randomly varying -1s and 1s. How can I do that? I was trying randi([-1:2:1],30,1) but that gives me zeros too and I don't want zeros, only -1 and 1. Thanks

 採用された回答

John Petersen
John Petersen 2012 年 7 月 5 日

1 投票

x = 2*round(rand(30,1)) - 1;

3 件のコメント

Isabel
Isabel 2012 年 7 月 5 日
This gives me a column of zeros only. Thanks anyways
John Petersen
John Petersen 2012 年 7 月 5 日
編集済み: John Petersen 2012 年 7 月 5 日
No it doesn't. Maybe you didn't grab the whole line?
Isabel
Isabel 2012 年 7 月 5 日
Sorry, it does work, my bad. I think I din't copy the whole formula or something. Thank you very much for your answer!

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2012 年 7 月 5 日
編集済み: Andrei Bobrov 2012 年 7 月 5 日

1 投票

eg
A = (rand(5) > .5) + 0;
A(~A) = -1;
or
A = 2*randi([0 1],30,1) - 1;

1 件のコメント

Isabel
Isabel 2012 年 7 月 5 日
Thanks! this works well

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

Orazio Sorgonà
Orazio Sorgonà 2022 年 4 月 2 日

0 投票

I use
A = -1^(randi([1,2]));

カテゴリ

ヘルプ センター および File ExchangeRandom Number Generation についてさらに検索

質問済み:

2012 年 7 月 5 日

回答済み:

2022 年 4 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by