我希望matlab中的变量能够存储(不要与显示混淆)最多4位小数.是否有内置命令?我尝试了以下 - 但这给出了一个错误:
a = [5.21365458 5.236985475 1.236598547 9.3265874];
k=1;
for i=1:length(a)
ast(k)=sprintf('%5.4f',a(i));
anum(k)=str2num(ast(k));
k=k+1;
end
Run Code Online (Sandbox Code Playgroud)
错误是:??? 下标分配尺寸不匹配.
您应该将数字四舍五入到小数点后四位.这在工作区中很容易做到:
>> x = rand(1,4)
x =
0.053378064308120 0.051670599653141 0.924623792776560 0.585692341974519
>> x = round(x*1e4) / 1e4
x =
0.053400000000000 0.051700000000000 0.924600000000000 0.585700000000000
Run Code Online (Sandbox Code Playgroud)
或者你可以写一个roundToDP(x,numberOfDecimalPlaces)为你做的功能:
function x = roundToDP(x,n)
% "Round the matrix x to n decimal places"
x = round(x * 10^n) / 10^n;
Run Code Online (Sandbox Code Playgroud)
现在您可以在工作区中使用该功能:
>> x = rand(1,4)
x =
0.810201981892601 0.165116049955136 0.457688639337064 0.985975706057179
>> roundToDP(x,4)
ans =
0.810200000000000 0.165100000000000 0.457700000000000 0.986000000000000
Run Code Online (Sandbox Code Playgroud)