Search code examples
matlabbitwise-or

Bitwise or over an array in Matlab?


I have a large array of binary numbers, and I want to do a bitwise OR over one dimension of the array:

X = [ 192, 96,  96,  2,  3
       12, 12, 128, 49, 14
       ....
    ];
union_of_bits_on_dim2 = [
       bitor(X(:,1), bitor(X(:,2), bitor(X(:,3), ... )))
    ];
ans = 
    [ 227
      191 
      ... ]

Is there a simple way of doing this? I'm actually working on an n-dimensional array. I tried bi2de but it flattens out my array and so the subscripting becomes complicated.

I could do it easily if matlab had a fold function but I don't think it does.


OK @Divakar asked for runnable code so to make it clear here is a long-winded version that might work for a 2D array.

function U=union_of_bits_on_dim2(X)
U=zeros(size(X,1),1);
for i=1:size(X,2)
  U=bitor(U,X(:,i));
end

Surely it be done without looping? I was of course hoping that bitor could take arbitrary numbers of arguments. Then it could have been done with mat2cell.


Solution

  • One vectorized approach -

    [m,n] =  size(X)  %// Get size of input array
    bd = dec2bin(X)-'0' %// Get binary digits
    
    %// Get cumulative "OR-ed" version with ANY(..,1)
    cum_or = reshape(any(permute(reshape(bd,m,n,[]),[2 3 1]),1),8,[]) 
    
    %// Finally convert to decimals
    U = 2.^(7: -1:0)*cum_or