how to randomly vary 2 numbers?

9 次查看(过去 30 天)
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
x = 2*round(rand(30,1)) - 1;
  3 个评论
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
eg
A = (rand(5) > .5) + 0;
A(~A) = -1;
or
A = 2*randi([0 1],30,1) - 1;

Orazio Sorgonà
Orazio Sorgonà 2022-4-2
I use
A = -1^(randi([1,2]));

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by