chsafouane
chsafouane

Reputation: 321

Truncating variable MATLAB

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!

Upvotes: 1

Views: 15687

Answers (2)

giusti
giusti

Reputation: 3538

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

Upvotes: 3

Wolfie
Wolfie

Reputation: 30101

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

Upvotes: 4

Related Questions