Home > Net >  Flip a bit in a matrix with a probability
Flip a bit in a matrix with a probability

Time:06-16

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.

CodePudding user response:

One solution, which is basically an implementation of the @bla suggestion:

% Random example input
x = rand(3)>0.5

% A vector with p(b) and p(a)
p = [0.1,0.2] % [p(b), p(a)]

% We map each value (0,1) with its probability and we check if it needs to be flipped.
is_flipped = p(x 1) > rand(3)

% Flip the value
res = xor(x,is_flipped)

CodePudding user response:

some hints:

so lets say flip is 1 and no flip is 0. the logical operation to flip is xor (look at the truth table if you never heard of it).

a probability a of can be arrived using Pa=rand(N,1)<=a, but that's for a vector of size Nx1. In your case you need to operate on the 1 and 0 separately.

CodePudding user response:

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
  • Related