如何在MATLAB中删除小数?
在本文中,我们将讨论在 MATLAB 中可以使用 sprintf()、fix()、floor()、round() 和 num2str() 函数完成的“去除小数点”,如下所示。
使用 sprintf()
sprintf()函数用于将格式化数据写入字符串。
Syntax:
sprintf(format, A)
Here, sprintf(format, A) is used to format the data in A over the specified format string.
例子:
Matlab
% MATLAB code for removal of
% decimal points using sprintf()
% Initializing some values
A = 3.000;
B = 1.420;
C = 0.023;
% Calling the sprintf() function over
% the above values
sprintf('%.f', A)
sprintf('%.f', B)
sprintf('%.f', C)
Matlab
% MATLAB code for removal
% of decimal points with fix()
% Initializing some values
A = 3.000;
B = 1.420;
C = 0.023;
% Calling the fix() function over
% the above values
fix(A)
fix(B)
fix(C)
Matlab
% MATLAB code for removal of
% decimal points using floor()
% Initializing some values
A = 2.000;
B = 1.790;
C = 0.9093;
% Calling the floor() function over
% the above values
floor(A)
floor(B)
floor(C)
Matlab
% MATLAB code for removal of
% decimal points using round()
% Initializing some values
A = 2.300;
B = 1.790;
C = 0.9093;
D = 0.093;
% Calling the round() function over
% the above values
round(A)
round(B)
round(C)
round(D)
Matlab
% MATLAB code for removal of
% decimal points without rounding
% Initializing some values
num2str(3.1455567, '%.0f')
输出:
ans = 3
ans = 1
ans = 0
使用修复()
fix()函数用于将指定值向零舍入。
Syntax:
fix(A)
Here, fix(A) is used to round the specified elements of A toward zero which results in an array of integers.
例子:
MATLAB
% MATLAB code for removal
% of decimal points with fix()
% Initializing some values
A = 3.000;
B = 1.420;
C = 0.023;
% Calling the fix() function over
% the above values
fix(A)
fix(B)
fix(C)
输出:
ans = 3
ans = 1
ans = 0
使用地板()
floor()函数用于将指定值向负无穷大舍入。
Syntax:
floor(A)
Here, floor(A) function is used to round the specified elements of A to the nearest integers less than or equal to A.
例子:
MATLAB
% MATLAB code for removal of
% decimal points using floor()
% Initializing some values
A = 2.000;
B = 1.790;
C = 0.9093;
% Calling the floor() function over
% the above values
floor(A)
floor(B)
floor(C)
输出:
ans = 2
ans = 1
ans = 0
使用 round()
round()函数用于将指定值四舍五入为其最接近的整数。
Syntax:
round(X)
Here, round(X) function is used to round the specified elements of X to their nearest integers.
示例 1:
MATLAB
% MATLAB code for removal of
% decimal points using round()
% Initializing some values
A = 2.300;
B = 1.790;
C = 0.9093;
D = 0.093;
% Calling the round() function over
% the above values
round(A)
round(B)
round(C)
round(D)
输出:
ans = 2
ans = 2
ans = 1
ans = 0
现在我们看看如何在不舍入的情况下删除小数位。为此,我们可以使用 num2str,它将数字转换为字符数组。
使用 num2str()
num2str()函数用于将指定的数字转换为字符数组。
Syntax: num2str(num)
Parameters: This function accepts a parameter.
- num: This is the specified number.
例子:
MATLAB
% MATLAB code for removal of
% decimal points without rounding
% Initializing some values
num2str(3.1455567, '%.0f')
输出:
ans = 3