matlab: keeping only first N digits of numbers

1.4k views Asked by At

I am trying to find a way in Matlab to truncate values of a vector, keeping only the first N digits (I don't want to round it, just to cut it.) of them. I wrote something which converts the values in strings, cut those and returns the number truncated, but it is too slow.

Any more clever solution?

Thanks a lot in advance!

2

There are 2 answers

0
Philippe K On

You could use the same logic than in this example:

X =-1.665584378238097

Y = round(X / 0.01) * 0.01

Y =

-1.670000000000000

And apply it to vectors/matrices.

4
brodoll On

Since you strictly say you do not want to round the number, here is one possible solution with the floor function, where I just drop the numbers after the specified decimal numbers N I want to keep:

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

Here's a sample run:

>> b=rand(1,2)

b =

   0.957166948242946   0.485375648722841

>> truncate(b,3)

ans =

   0.957000000000000   0.485000000000000

Note that if you are considering numbers greater than one, the function above would have to be slightly modified:

function trunc = truncate(x,N)
        %For numbers equal or greater than 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 the 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 is important to note that no checks were made to verify if the input to the function has in fact an ammount of digits greater than N, which I assumed to be true.