m2016b
m2016b

Reputation: 544

How to modify two bits in a codeword?

Principle : I have a codeword u and I want to change all the 2 bits among the 4 bits of u.

Example : if u = [1 1 0 0] , I want to obtain :

u1 = [0 0 0 0] ; u2 = [0 1 1 0] ; u3 = [0 1 0 1];
u4 = [1 0 1 0] ; u5 = [1 0 0 1] ; u6 = [1 1 1 1];

Program :

u = rand(1,4)>0.5
for i = 1:size(u,2)
    if u(:,1)==0 && u(:,2)==0
       u1 = [1 1 u(:,3) u(:,4)];
    elseif u(:,1)==1 && u(:,2)==0
       u1 = [0 1 u(:,3) u(:,4)];
    elseif u(:,1)==0 && u(:,2)==1
       u1 = [1 0 u(:,3) u(:,4)];
    elseif u(:,1)==1 && u(:,2)==1
       u1 = [0 0 u(:,3) u(:,4)];
    end

    if u(:,1)==0 && u(:,3)==0
       u2 = [1 u(:,2) 1 u(:,4)];
    elseif u(:,1)==1 && u(:,3)==0
       u2 = [0 u(:,2) 1 u(:,4)];
    elseif u(:,1)==0 && u(:,3)==1
       u2 = [1 u(:,2) 0 u(:,4)];
    elseif u(:,1)==1 && u(:,3)==1
       u2 = [0 u(:,2) 0 u(:,4)];
    end

    if u(:,1)==0 && u(:,4)==0
       u3 = [1 u(:,2) u(:,3) 1];
    elseif u(:,1)==1 && u(:,4)==0
       u3 = [0 u(:,2) u(:,3) 1];
    elseif u(:,1)==0 && u(:,4)==1
       u3 = [1 u(:,2) u(:,3) 0];
    elseif u(:,1)==1 && u(:,4)==1
       u3 = [0 u(:,2) u(:,3) 0];
    end

    if u(:,2)==0 && u(:,3)==0
       u4 = [u(:,1) 1 1 u(:,4)];
    elseif u(:,2)==1 && u(:,3)==0
       u4 = [u(:,1) 0 1 u(:,4)];
    elseif u(:,2)==0 && u(:,4)==1
       u4 = [u(:,1) 1 0 u(:,4)];
    elseif u(:,2)==1 && u(:,3)==1
       u4 = [u(:,1) 0 0 u(:,4)];
    end

    if u(:,2)==0 && u(:,4)==0
        u5 = [u(:,1) 1 u(:,3) 1];
    elseif u(:,2)==1 && u(:,4)==0
        u5 = [u(:,1) 0 u(:,3) 1];
    elseif u(:,2)==0 && u(:,4)==1
        u5 = [u(:,1) 1 u(:,3) 0];
    elseif u(:,2)==1 && u(:,4)==1
        u5 = [u(:,1) 0 u(:,3) 0];
    end

    if u(:,3)==0 && u(:,4)==0
       u6 =[u(:,1) u(:,2) 1 1];
    elseif u(:,3)==1 && u(:,4)==0
       u6 =[u(:,1) u(:,2) 0 1];
    elseif u(:,3)==0 && u(:,4)==1
       u6 =[u(:,1) u(:,2) 1 0];
    elseif u(:,3)==1 && u(:,4)==1
       u6 =[u(:,1) u(:,2) 0 0];
    end
 end 

I need to generalize my program to all lengths of u and make it shorter, because if the length of u is large it will be difficult to proceed in this way.

Someone can help me to generalize my program and make my it shorter?

Thanks!

Upvotes: 0

Views: 51

Answers (1)

OmG
OmG

Reputation: 18838

A simple solution could be:

  u = [1 1 0 0];
  us = []; % all possible u
  k = 2;
  n = length(u);
  C = nchoosek(1:n,k);
  notC = ~u(C); % flip value of the specified elements of u
  for i = 1:size(notC,1)
      uTemp = u;
      uTemp(C(i,:)) = ~u(C(i,:));
      us = [us; uTemp];
  end

Upvotes: 2

Related Questions