具有许多输入的Bitor等按位命令?

hhh*_*hhh 5 matlab bit-manipulation

Matlab只使用按位命令输入两个输入,例如bitor.bitor(1,2)返回3并且bitor(1,2,4)不返回7但是:

ASSUMEDTYPE必须是整数类型名称.

目前,我创建for循环基本上创建一个按位命令,以根据需要获取尽可能多的输入.我觉得这种东西的for-loops是重新发明轮子.

是否有一些简单的方法来创建具有许多输入的按位运算?

目前有一些随机数的例子,必须返回127

indices=[1,23,45,7,89,100];
indicesOR=0;
for term=1:length(indices)
    indicesOR=bitor(indicesOR,indices(term));
end
Run Code Online (Sandbox Code Playgroud)

Lui*_*ndo 2

如果您不介意涉及字符串(可能会很慢):

indicesOR  = bin2dec(char(double(any(dec2bin(indices)-'0'))+'0'));
Run Code Online (Sandbox Code Playgroud)

这用于dec2bin转换为'0'and的字符串'1';通过减法转换为数字 0 和 1 '0'any使用;按列应用“或”运算 然后再转换回来。

对于 AND(而不是 OR):替换anyall

indicesAND = bin2dec(char(double(all(dec2bin(indices)-'0'))+'0'));
Run Code Online (Sandbox Code Playgroud)

对于异或:使用rem(sum(...),2)

indicesXOR = bin2dec(char(double(rem(sum(dec2bin(indices)-'0'),2))+'0'))
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚发现了函数de2bibi2de(通信工具箱),它们避免使用字符串。不过,他们的速度似乎慢了一些!

indicesOR  = bi2de(double(any(de2bi(indices))));
indicesAND = bi2de(double(all(de2bi(indices))));
indicesXOR = bi2de(double(rem(sum((de2bi(indices))));
Run Code Online (Sandbox Code Playgroud)

另一种方法是定义递归函数,利用 AND、OR、XOR 运算是(按位)关联的事实,即 x OR y OR z 等于 (x OR y) OR z。要应用的操作作为函数句柄传递。

function r = bafun(v, f)
%BAFUN  Binary Associative Function
%   r = BAFUN(v,f)
%   v is a vector with at least two elements
%   f is a handle to a function that operates on two numbers

if numel(v) > 2
    r = bafun([f(v(1), v(2)) v(3:end)], f);
else
    r = f(v(1), v(2));
end
Run Code Online (Sandbox Code Playgroud)

例子:

>> bafun([1,23,45,7,89,100], @bitor)
ans =
   127
Run Code Online (Sandbox Code Playgroud)