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

后端 未结 5 538
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  鱼传尺愫
    2021-01-23 06:26

    Thanks for these many helpful answers. I figure this topic might be general enough it may well deserve a comparison.

    In my setup ( Windows8.4 x64 i74820k cpu and with R2014a) the fastest version is consistently:

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

    Being half an order of magnitude faster than the slowest solution. Hope this helps.

    comparison: figure comparing execution times for pseudo-random sign generation

    code:

    L=[];
    for expon=0:6
        for mant=1:9
        L=cat(1,L,mant*power(10,expon));
        end
    end
    clear expon mant
    
    t1=zeros(length(L),1);
    x=2*round(rand(L(1),1))-1;
    for li=1:length(L)
        tic,
        x=2*round(rand(L(li),1))-1;
        t1(li)=toc;
    end
    
    t2=zeros(length(L),1);
    x=(rand(L(1),1)>0.5)*2-1;
    for li=1:length(L)
        tic,
        x=(rand(L(li),1)>0.5)*2-1;
        t2(li)=toc;
    end
    
    t3=zeros(length(L),1);
    x=(randi([0,1],L(1),1)>0.5)*2-1;
    for li=1:length(L)
        tic,
        x=(randi([0,1],L(li),1)>0.5)*2-1;
        t3(li)=toc;
    end
    
    t4=zeros(length(L),1);
    x=rand(L(1),1);ind=x>=0.5;x(ind)=1;x(~ind)=-1;
    for li=1:length(L)
        tic,
        x=rand(L(li),1);
        ind=x>=0.5;
        x(ind)=1;
        x(~ind)=-1;
        t4(li)=toc;
    end
    
    t5=zeros(length(L),1);
    x=sign(randn(L(1),1));
    for li=1:length(L)
        tic,
        x=sign(randn(L(li),1));
        x(x==0)=1;
        t5(li)=toc;
    end
    
    t6=zeros(length(L),1);
    vec = [-1 1];
    x=vec(randi(numel(vec),L(1),1));
    for li=1:length(L)
        tic,
        x=vec(randi(numel(vec),L(li),1));
        t6(li)=toc;
    end
    
    t7=zeros(length(L),1);
    x=2*randi(2,L(1),1)-3;
    for li=1:length(L)
        tic,
        x=2*randi(2,L(li),1)-3;
        t7(li)=toc;
    end
    
    t8=zeros(length(L),1);
    x=randsample([-1 1],L(1),true);
    for li=1:length(L)
        tic,
        x=randsample([-1 1],L(li),true);
        t8(li)=toc;
    end
    
    clear x vec ind li
    
    figure,
    loglog(L,[t1 t2 t3 t4 t5 t6 t7 t8],'.-','linewidth',2)
    grid on 
    grid minor
    title('Generating pseudo-random sequence +1/-1')
    ylabel('Exec. Time [s]')
    xlabel('Output Vector Length')
    T{1}='x=2*round(rand(L(1),1))-1';
    T{2}='x=(rand(L(1),1)>0.5)*2-1';
    T{3}='x=(randi([0,1],L(1),1)>0.5)*2-1';
    T{4}='x=rand(L(1),1);ind=x>=0.5;x(ind)=1;x(~ind)=-1';
    T{5}='x=sign(randn(L(1),1))';
    T{6}='vec=[-1 1];x=vec(randi(numel(vec),L(1),1))';
    T{7}='x=2*randi(2,L(1),1)-3';
    T{8}='x=randsample([-1 1],L(1),true)';
    legend(T,'location','northwest')
    

提交回复
热议问题