Search code examples
matlabbinaryoctavenumericradix

Matlab/Octave bitget function for any base


Need function like bitget, but for any base.

Would be nice to have as well:

  1. array input and array bit selection
  2. anonymous function

Solution

    1. Implementaion for Matlab (for Octave will work as well, but I recommend the 2nd option):

      % 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. Implementaion for Octave: as far as Octave supports default values for inline function, it completely covered by de2bs function (see 2nd option)