How to implement Benford's law in MATLAB

I want to implement a version of Benford's law ( http://en.wikipedia.org/wiki/Benford%27s_law ) which basically asks the first digit of the number to do a distribution analysis.

1934---> 1
0.04 ---> 4
-56 ---> 5

How do you do this in MATLAB?

+3
source share
4 answers

Several ways to do this ...

  • Using REGEXP :

    wholeNumber = 1934;                      %# Your number
    numberString = num2str(wholeNumber,16);  %# Convert to a string
    matches = regexp(numberString,'[1-9]','match');  %# Find matches
    firstNumber = str2double(matches{1});  %# Convert the first match to a double
    
  • Using ISMEMBER :

    wholeNumber = 0.04;                      %# Your number
    numberString = num2str(wholeNumber,16);  %# Convert to a string
    isInSet = ismember(numberString,'123456789');  %# Find numbers that are
                                                   %#  between 1 and 9
    numberIndex = find(isInSet,1);           %# Get the first number index
    firstNumber = str2double(numberString(numberIndex));  %# Convert to a double
    

EDIT:

MathWorks. . , , - , :

numberVector = [1934 0.04 -56];
numberStrings = cellstr(num2str(numberVector(:),16));
firstIndices = regexp(numberStrings,'[1-9]','once');
firstNumbers = cellfun(@(s,i) s(i),numberStrings,firstIndices);
+2
function res = first_digit(number)
    number = abs(number);
    res = floor(number / (10 ^ floor(log10(number))));
end

(. gnovice )

+4

Using the log10 and floor functions,

floor(x./10.^floor(log10(x)))

returns the first digit of all elements in the array.

+1
source

Let me add another string solution (also vectorized):

FirstDigit = @(n) sscanf(num2str(abs(n(:)),'%e'), '%1d', numel(n));

and tested in the cases mentioned here:

>> FirstDigit( [1934 0.04 -56 eps(realmin)] )
ans =
     1
     4
     5
     4
0
source

Source: https://habr.com/ru/post/1740363/


All Articles