Search code examples
matlabbit

Flip a bit in a matrix with a probability


I want to change a bit in a matrix with a given probability.

Let say I have [1 0 1; 1 1 0; 0 0 1]

And I want to flip bit 1 to bit 0 with a probability of a and flip bit 0 to bit 1 with a probability of b. And then create a new 3x3 matrix with new values.


Solution

  • I have come up with a solution and hope this helps other people.

    a = [1 0 0 ; 1 1 1 ; 0 0 0];
    row = 3;
    column = 3;
    prob1to0 = 0.7; %probability that bit1 flips
    prob0to1 = 0.1; %probability that bit0 flips
    
    flip1to0 = rand(3) <= prob1to0; 
    flip0to1 = rand(3) <= prob0to1;
    
    a_new = zeros(3,3);
    
    for m=1:3
        for n=1:3
            if (a(m,n) == 1) && (flip1to0(m,n)==1) 
                a_new(m,n)=a(m,n)-1;
            elseif (a(m,n) == 0) && (flip0to1(m,n) == 1)
                a_new(m,n)=a(m,n)+1;
            else 
                a_new(m,n)=a(m,n);
            end
        end
    end