How to extract leading non-zero digit?

조회 수: 20 (최근 30일)
John Booker
John Booker 2011년 1월 4일
댓글: Asif Newaz 2019년 11월 22일
I'm working on a research problem related to Benford's Law which states that the distribution of leading digits is not random. This is probably because many things grow logarithmically. I am trying to extract the leading digit from these vectors below:
10 --> 1
13 --> 1
0.3 --> 3
-4 --> 4
-5 --> 5
-0.006 --> 6
Input will be a vector
x = [1 0.3 -2 0.001 -0.0006, 582398, 3020];
Output should be
y = [1 3 2 1 6 5 3];
Any help?

채택된 답변

Walter Roberson
Walter Roberson 2011년 1월 20일
The answer is complicated because numbers such as 0.0006 have no exact representation in binary floating point number, and the closest number that can be represented might not have the same leading binary digit.
If one does NOT take that factor in to account, then:
y = floor(abs(x) ./ 10.^floor(log10(abs(x))));
  댓글 수: 2
Jan
Jan 2012년 6월 28일
I suggest to accept this one.
John Booker
John Booker 2013년 8월 1일
Sorry it took me so long to accept. I stole this question from Ned before Answers launched and forgot about it =).

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Ned Gulley
Ned Gulley 2011년 1월 11일
You'll probably need to do some kind of textual manipulation. Here's one way to do it.
function y = leadingDigit(x)
s = sprintf('%1.2e\n',abs(x));
y = s(1:(length(s)/length(x)):end)-48;
end

Daniel Shub
Daniel Shub 2012년 6월 28일
Is this really the first question on Answers? I was going to use our new magic power and start accepting answers. The only problem is I think there is now a better answer to this question on Loren's blog.
  댓글 수: 1
Jan
Jan 2012년 6월 28일
I thought of accepting this answer, because it contains a link to good solutions. But actually the method shown by Walter hits the point (and is found in this blog also). Ned's method is more efficient than STR2DOUBLE, but a clean numerical approach is moire direct for a numerical question.

댓글을 달려면 로그인하십시오.


Oleg Komarov
Oleg Komarov 2012년 9월 5일
Another solution based on regexp (from this question):
regexp(num2str(x), '(?<=(^|\s+)[\-\.0]*)[1-9](?=[\d\.]*)', 'match')
  댓글 수: 1
Asif Newaz
Asif Newaz 2019년 11월 22일
can u explain the 'expression'... i've found regexp quite complicated but very useful

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by