Truncate decimal numbers in matlab?

Is there a quick and easy way to truncate a decimal number, say, more than 4 digits, in MATLAB?

round()doesn't help, it's still rounded. I have to use it for a loop, so the fastest way is evaluated.

Thanks for your details.

+4
source share
5 answers

Another option:

x = -3.141592653;
x_trun = x - rem(x,0.0001)

x_trun =

    -3.1415

Kudos to gnovice for updates.

In general, for ndecimal places:

x_trun = x - rem(x,10^-n)
+6
source

Here's one method for truncating ddigits after a decimal.

val = 1.234567;
d = 4;
val_trunc = fix(val*10^d)/10^d

Result

val_trunc =

   1.2345

If you know that is valpositive, then it floor()will work instead fix().

+8
source

, 5 , .

, x n ,

round(x - sign(x)*.5/10^n, n)

( @gnovice , sign(x), .)

,

format long
x = 3.141592653589793;
for n = 2:5
    result = round(x - sign(x)*.5/10^n, n);
    disp(result)
end

   3.140000000000000
   3.141000000000000
   3.141500000000000
   3.141590000000000
+4

, , 3 , . . . x , timeit .

function benchie()
    % Set up iteration variables
    K = 17;  n = 4;  T = zeros(K,3);
    for k = 1:K
        x = rand(2^k,1);
        % Define the three truncation functions
        LuisRound = @() round(x - 0.5/10^n, n);
        JodagFix = @() fix(x*10^n)/10^n;
        InfoRem = @() x - rem(x,10^-n);
        % Time each function
        T(k,1) = timeit(LuisRound);
        T(k,2) = timeit(JodagFix);
        T(k,3) = timeit(InfoRem);
    end
    % Plot results
    figure
    plot(2.^(1:K), T); legend('LuisRound', 'JodagFix', 'InfoRem');
    grid on; xlabel('number of elements in x'); ylabel('time taken');
end

:

plot

fix, jodag, , - n :

function y = trunc(x, n)
%% Truncate matrix/scalar x to n decimal places
    if nargin < 2; n = 0; end; % default to standard fix behaviour if no n given
    y = fix(x*10^n)/10^n;      % return value truncated to n decimal places
end

:

>> trunc([pi, 10.45, 1.9], 4)
>> ans = [3.1415   10.4500    1.9000]
>> trunc([pi, 10.45, 1.9], 1)
>> ans = [3.1      10.4       1.9] 
+4

round2:

function result = round2(x,accuracy)
    if nargin<2, accuracy=1; end %default accuracy 1 same as 'round'
    if accuracy<=0, accuracy=1e-6; end
    result=round(x/accuracy)*accuracy;
end

Normal use: round2(3.14159,0.01)But you can also use it to round for every other multiplier, for example: round2(number,2)will round to an even number, or round2(number,10)etc.

0
source

Source: https://habr.com/ru/post/1684337/


All Articles