20

I have a variable, tauMax, that I want to round up to the nearest power of ten(1, 10, 100, 1000...). I am using the below expression to find the closest integer to the max value in the tau array. I am finding the max value because I am trying to calculate the power of ten that should be the x axis cutoff. In this cause, tauMax is equal to 756, so I want to have an expression that outputs either 1000, or 3(for 10^3).

tauMax = round(max(tau));

I'd really appreciate any help!

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Alex Nichols
  • 876
  • 5
  • 12
  • 23
  • 1
    You could also do this I believe based off of the number of digits. –  Jul 20 '11 at 22:43
  • That's a great idea. Do you know what command i would use to find the number of digits in a given number? – Alex Nichols Jul 20 '11 at 22:47
  • @Alex Nichols - Since you're talking base 10 just use `log10` (see my answer below). – b3. Jul 20 '11 at 22:49
  • Seems to be some different ways to do that: http://www.mathworks.co.jp/matlabcentral/answers/10795-counting-the-number-of-digits, but the other method may be easier. –  Jul 20 '11 at 22:50

3 Answers3

42

Since you're talking base 10, you could just use log10 to get the number of digits.

How about:

>> ceil(log10(756))

ans =

     3
Hannele
  • 9,301
  • 6
  • 48
  • 68
b3.
  • 7,094
  • 2
  • 33
  • 48
7

I don't really do Matlab, but the usual way to do this in any language I do know is: take the logarithm base 10, then round up that number to the nearest integer, then compute 10 to the power of that number. In Python:

from math import ceil, log

def ceil_power_of_10(n):
    exp = log(n, 10)
    exp = ceil(exp)
    return 10**exp

>>> print(ceil_power_of_10(1024))  # prints 10000
steveha
  • 74,789
  • 21
  • 92
  • 117
-2

You could also look at the source of the built-in Matlab function nextpow2(N) (simply open nextpow2.m) to see how Mathworks engineers implemented this for a power of 2 and create a new function adapting this source to a power of 10.

http://www.mathworks.it/it/help/matlab/ref/nextpow2.html

Hermann
  • 7
  • 2