matlab: keeping only first N digits of numbers -


i trying find way in matlab truncate values of vector, keeping first n digits (i don't want round it, cut it.) of them. wrote converts values in strings, cut , returns number truncated, slow.

any more clever solution?

thanks lot in advance!

since strictly not want round number, here 1 possible solution floor function, drop numbers after specified decimal numbers n want keep:

function trunc = truncate(x,n)     trunc = floor(x*10^n)/10^n; end 

here's sample run:

>> b=rand(1,2)  b =     0.957166948242946   0.485375648722841  >> truncate(b,3)  ans =     0.957000000000000   0.485000000000000 

note if considering numbers greater one, function above have modified:

function trunc = truncate(x,n)         %for numbers equal or greater 1, getting n first digits         trunc=x;         idx = x>=1;         trunc(idx) = floor(x(idx)/10^n);          %for decimals, keeping n first digits after comma         trunc(~idx) = floor(x(~idx)*10^n)/10^n; end 

another run of truncate function:

>> b=[123 rand(1,2)]  b =     1.0e+02 *     1.230000000000000   0.004217612826263   0.009157355251891  >> truncate(b,2)  ans =     1.000000000000000   0.420000000000000   0.910000000000000 

it important note no checks made verify if input function has in fact ammount of digits greater n, assumed true.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -