poster
2019-12-10, 20:30
我想实现一个本福德定律( http://en.wikipedia.org/wiki/Benford%27s_law )版本,该版本基本上要求数字的第一位数字来进行分布分析。
1934---> 1 0.04 ---> 4 -56 ---> 5 您如何在MATLAB中执行此操作?
回答:
您可以通过几种方法执行此操作...
使用REGEXP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html) :
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
使用ISMEMBER (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ismember.html) :
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
编辑:
在MathWorks的一个博客 (http://blogs.mathworks.com/videos/2010/04/08/puzzler-benfords-law/)上已经对此主题进行了一些讨论。那里提供了一些有趣的其他解决方案。提出的一个问题是矢量化解决方案,因此我想出了一个矢量化版本:
numberVector = [1934 0.04 -56]; numberStrings = cellstr(num2str(numberVector(:),16)); firstIndices = regexp(numberStrings,'[1-9]','once'); firstNumbers = cellfun(@(s,i) s(i),numberStrings,firstIndices);
更多&回答... (https://stackoverflow.com/questions/2602365)
1934---> 1 0.04 ---> 4 -56 ---> 5 您如何在MATLAB中执行此操作?
回答:
您可以通过几种方法执行此操作...
使用REGEXP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html) :
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
使用ISMEMBER (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ismember.html) :
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
编辑:
在MathWorks的一个博客 (http://blogs.mathworks.com/videos/2010/04/08/puzzler-benfords-law/)上已经对此主题进行了一些讨论。那里提供了一些有趣的其他解决方案。提出的一个问题是矢量化解决方案,因此我想出了一个矢量化版本:
numberVector = [1934 0.04 -56]; numberStrings = cellstr(num2str(numberVector(:),16)); firstIndices = regexp(numberStrings,'[1-9]','once'); firstNumbers = cellfun(@(s,i) s(i),numberStrings,firstIndices);
更多&回答... (https://stackoverflow.com/questions/2602365)