Truncating variable MATLAB

大憨熊 提交于 2019-12-13 07:07:51

问题


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



来源:https://stackoverflow.com/questions/41549814/truncating-variable-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!