【问题标题】:Bitwise or over an array in Matlab?Matlab中的按位或数组?
【发布时间】:2015-02-26 15:52:32
【问题描述】:

我有一个大的二进制数数组,我想对数组的一维进行按位或:

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 完成。

【问题讨论】:

  • 您能否发布可运行的代码以获取union_of_bits_on_dim2
  • OK 给出了一个使用循环的例子
  • 你的号码是什么数据类型?双 |整数8 |整数 16 |整数32 |整数64 | uint8 | uint16 | uint32 | uint64?还是您只想要无符号整数的通常二进制表示?

标签: matlab bitwise-or


【解决方案1】:

一种矢量化方法 -

[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

【讨论】:

  • 谢谢你的作品。但它比我希望的要复杂! (对于 n 维更是如此)
  • @SanjayManohar 有了这些重塑和排列,我猜它看起来可能是这样的!但是,如果您有机会,请告诉我们您可能会通过这个获得任何加速?谢谢!
【解决方案2】:

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

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

【讨论】:

  • 谢谢,我没听说过有用的shiftdim
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
相关资源
最近更新 更多