how to randomly vary 2 numbers?

조회 수: 9 (최근 30일)
Isabel
Isabel 2012년 7월 5일
답변: Orazio Sorgonà 2022년 4월 2일
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;
  댓글 수: 1
Isabel
Isabel 2012년 7월 5일
Thanks! this works well

댓글을 달려면 로그인하십시오.


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