Matlab/Octave 任意基数的 bitget 函数

Matlab/Octave bitget function for any base

需要类似 bitget 的功能,但适用于任何基础。

最好有:

  1. 数组输入和数组位选择
  2. 匿名函数
  1. Matlab 的实现(对于 Octave 也可以,但是我推荐第二个选项):

    % Anonymous function digget
    % dig = digget(dec, base, pos)                
    %   dig  - returns the value of the digits in positions (pos) for numbers (dec)
    %          coverted to the defined base (for base=2 behaves similar to bitget) 
    %   dec  - initial decimal numbers vector
    %   base - base to convert (for binary base = 2 )
    %   pos  - array of positions 
    %          if pos = [(ceil( log2(max(dec(:)))/log2(base)) ):-1:1] 
    %          behaves similar as dec2base function
    %
    % Examples:
    % dig = digget(1:8, 2, 2:-1:1)
    %
    % dig =
    %
    %   0   1
    %   1   0
    %   1   1
    %   0   0
    %   0   1
    %   1   0
    %   1   1
    %   0   0
    % 
    %
    % dig = digget(8:15, 13, 3:-1:1)
    %
    % dig =
    %
    %    0    0    8
    %    0    0    9
    %    0    0   10
    %    0    0   11
    %    0    0   12
    %    0    1    0
    %    0    1    1
    %    0    1    2
    
    digget = @(dec,base,pbit) sum(rem(dec(:),base.*pbit)>= permute((1:base-1)'*pbit,[3,2,1]),3);
    digget = @(dec,base, bit) digget(dec,base,base.^(bit-1));
    
  2. Octave的实现: 至于 Octave 支持内联函数的默认值,de2bs 完全涵盖了它 函数(见第二个选项)