Search code examples
matlabpsychtoolbox

Matrix of 0s and 1s Where Assignment in Subsequent Rows are Contingent on the Previous Row


I'd like to create a Matrix in MATLAB where:

The First row consists of a random arrangement of 0s and 1s, split evenly (i.e. 50-50).

The Second row randomly assigns zeros to 50% of the 0s and 1s in the first row, and ones to the remaining 50%.

The Third row randomly assigns zeros to 50% of the 0s and 1s in the second row, and ones to the remaining 50%.

Non-randomized Example:

0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1  
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1  
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1

Any suggestions?


Solution

  • A solution based on checking whether numbers are bigger or smaller than the median. As long as the number of columns tested is even, exactly half of a set of random doubles will be bigger than the median, and half will be smaller. This guarantees that there's exactly 50% of bits get flipped.

    nRows = 3;
    nCols = 16; %# divisible by 4
    
    %# seed the array
    %# assume that the numbers in each row are unique (very, very likely)
    array = rand(nRows,nCols); 
    
    
    out = false(nRows,nCols);
    
    %# first row is special
    out(1,:) = array(1,:) > median(array(1,:));
    
    %# for the rest of the row, check median for the zeros/ones in the previous row
    for iRow = 2:nRows
        zeroIdx = out(iRow-1,:) == 0;
        %# > or < do not matter, both will replace zeros/ones 
        %# and replace with exactly half zeros and half ones
        out(iRow,zeroIdx) = array(iRow,zeroIdx) > median(array(iRow,zeroIdx));
        out(iRow,~zeroIdx) = array(iRow,~zeroIdx) > median(array(iRow,~zeroIdx));
    end