在 Matlab 中按位还是在数组上?
Bitwise or over an array in Matlab?
我有一大堆二进制数,我想对数组的一维进行按位或操作:
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 要求提供可运行的代码,所以这里要说清楚的是一个可能适用于二维数组的冗长版本。
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
.
完成
我不知道有什么函数可以自动执行此操作。但是,您可以遍历您感兴趣的维度:
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
一种矢量化方法 -
[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
我有一大堆二进制数,我想对数组的一维进行按位或操作:
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 要求提供可运行的代码,所以这里要说清楚的是一个可能适用于二维数组的冗长版本。
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
.
我不知道有什么函数可以自动执行此操作。但是,您可以遍历您感兴趣的维度:
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
一种矢量化方法 -
[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