在Matlab中按位或在数组上?

时间:2015-02-26 15:52:32

标签: matlab bitwise-or

我有一大堆二进制数,我想在数组的一个维度上进行按位OR:

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 
      ... ]

有一种简单的方法吗?我实际上在研究一个n维数组。我尝试了bi2de,但它使我的数组变平,因此下标变得复杂。

如果matlab有fold函数,我可以轻松完成,但我不认为它。


确定@Divakar要求提供可运行的代码,以便明确说明这是一个可能适用于2D数组的冗长版本。

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

当然可以在没有循环的情况下完成?我当然希望bitor可以接受任意数量的论点。然后可以使用mat2cell完成。

2 个答案:

答案 0 :(得分:2)

一种矢量化方法 -

[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

答案 1 :(得分:1)

我不知道任何可以自动执行此操作的功能。但是,您可以遍历您感兴趣的维度:

function result = bitor2d(A)
    result = A(1,:);
    for i=2:size(A,1)
        result = bitor(result,A(i,:));
    end
end

如果你的数组有2个以上的维度,那么你需要准备它只有2个。

function result = bitornd(A,whichdimension)
    B = shiftdim(A,whichdimension-1); % change dimensions order
    s = size(B);
    B = reshape(B,s(1),[]);  % back to the original shape
    result = bitor2d(B);
    s(1) = 1;
    result = reshape(result,s); % back to the original shape
    result = shiftdim(result,1-whichdimension); % back to the original dimension order
end