如何只在matlab变量中存储最多4个小数位? [英] How to store only upto 4 decimal places in a matlab variable?

查看:442
本文介绍了如何只在matlab变量中存储最多4个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望matlab中的变量最多可以存储4个小数位(不要与显示混淆). 是否有内置命令? 我尝试了以下操作-但这给出了错误:

I want a variable in matlab to store(not to be confused with display) only upto 4 decimal places. Is there an inbuilt command for it? I tried the following - but this gives an error:

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

错误是:???下标的分配维度不匹配.

error is : ??? Subscripted assignment dimension mismatch.

推荐答案

您应将数字四舍五入到小数点后四位.这在工作空间中很容易做到:

You should round the numbers to four decimal places. This is easy to do in the workspace:

>> 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

或者您可以编写一个函数roundToDP(x,numberOfDecimalPlaces)来为您完成此功能:

or you could write a function roundToDP(x,numberOfDecimalPlaces) that does it for you:

function x = roundToDP(x,n)
% "Round the matrix x to n decimal places"
x = round(x * 10^n) / 10^n;

现在您可以在工作空间中使用该功能:

now you can use that function in the workspace:

>> 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

这篇关于如何只在matlab变量中存储最多4个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆