Truncating variable MATLAB

2019-09-19 06:46发布

问题:

I'm working with an array A in MATLAB. The values in this array have up to 5 decimals. I would like to truncate those values to a less number of decimal.

Is there a way to accomplish this?

Thanks!

回答1:

For some reason, Matlab's "truncate" function is called fix. So

>> fix(3.5) 
ans = 3

>> fix(-3.5)
ans = -3

To truncate, round, floor, or ceil anything to a given number of decimals, multiply by powers of tens, truncate, round, floor, or ceil, and then divide the result by powers of tens.

So:

>> fix(123.456 * 10^2)
ans = 12345

>> ans / 10^2
ans = 123.45


回答2:

Rounding Digits:

To round a value (or matrix) to given number of decimal places, use round, for example to 2 decimal places...

round(1.2345, 2) 

ans = 1.2300

To also not display the trailing zeros, first change the format to shortg

format shortg

round(1.2345, 2)

ans = 1.23

The format compact can achieve similar results, choose the best one to suit your needs based on the documentation below.

Documentation:

Round: https://uk.mathworks.com/help/matlab/ref/round.html

Format: https://uk.mathworks.com/help/matlab/ref/format.html