Generating a Pseudo-random sequence of plus/minus 1 integers

后端 未结 5 545
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 06:24

Can anybody help me create a simple pseudo-random sequence of +-1 integers with length 1000 using Matlab?

I.e. a sequence such as

-1 -1 1 1 -1 -1 1 -1 -         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 06:43

    Some alternatives:

    x = 2*randi(2, 1000, 1)-3; %// generate 1 and 2 values, and transform to -1 and 1
    x = 2*(rand(1, 1000, 1)<=.5)-1; %// similar to Rayryeng's answer but in one step
    x = randsample([-1 1], 1000, true); %// sample with replacement from the set [-1 1]
    

提交回复
热议问题