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
Post a Comment