Clear Filters
Clear Filters

How do you create the number as mentioned below?

1 view (last 30 days)
If we write all positive integers in a row (in our decimal system) we get 123456789101112131415161718192021222324252627282930
Write a function that returns the n-th digit of this gigantic number.
  2 Comments
Juull01
Juull01 on 8 Oct 2016
I know how to solve the last part, but I really have no idea how to create that hugh number in Matlab.
Thanks in advance

Sign in to comment.

Accepted Answer

Massimo Zanetti
Massimo Zanetti on 8 Oct 2016
Here it is
m=1:30;
n=12;
s=regexprep(num2str(m),' ','')
s(n)
  2 Comments
Juull01
Juull01 on 8 Oct 2016
Thank so much for your help! I really appreciate it I worked on it for like 2 hours and couldn't get the answer.
Massimo Zanetti
Massimo Zanetti on 8 Oct 2016
If you like my answer, please accept it. :)

Sign in to comment.

More Answers (3)

Marc Jakobi
Marc Jakobi on 8 Oct 2016
I won't tell you how to do it since this sounds like homework, but here are some functions that may help you.
str2double() % convert string to double
num2str() % convert double to string
to combine two strings:
a = 'a';
b = 'b';
ab = [a, b];
returns
'ab'
and
ab(2)
returns
ab(2) = 'b'

Star Strider
Star Strider on 8 Oct 2016
Without using strings at all, this works strictly numerically:
M1 = repmat([0:9], 10, 1);
M2 = repmat([0:9]', 1, 10);
M3 = cat(3,M1, M2);
M4 = reshape(M3, [], 2);
M5 = reshape(M4', 1, []);
Out = [1:9 M5(21:end)]

Walter Roberson
Walter Roberson on 9 Oct 2016
Edited: Walter Roberson on 9 Oct 2016
For amusement, a Maple version of the general solution, using direct numeric calculations without creating the intermediate values.
H := proc (M)
local min_numdig, contrib_from_min, leftover, dp1, base_number, dig, dig_offset;
min_numdig := floor(((1/9)*ln(10)+LambertW((1/90)*ln(10)*(9*M-1)*10^(8/9)))/ln(10));
dp1 := min_numdig+1;
contrib_from_min := (1/90)*10^dp1*(9*min_numdig-1)+1/9;
leftover := M-contrib_from_min;
if leftover = 0
then
dig := "9"
else
base_number := 10^min_numdig-1+floor(leftover/dp1);
dig_offset := `mod`(leftover, dp1);
if dig_offset = 0
then
dig_offset := dp1
else
base_number := base_number+1
end if;
dig := sprintf("%d", base_number)[dig_offset]
end if;
dig
end proc;
Note: this fails on 0 due to both a Maple technicality and a logic bug. The mathematics of it is presented without proof.
No MATLAB version of this will be provided, as the question is obviously a homework question.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!