Round double value to 2 decimal
古いコメントを表示
Hi all,
I'm trying to round an array of double values to 2 decimals.
This is my code:
for k=1:n,
y(k)=k*st;
y(k)= sprintf('%0.2f', y(k));
x(k) = sqrt(d^2+(2*y(k))^2)-d;
x(k)= sprintf('%0.2f', x(k));
end
I got the following error message:
In an assignment A(I) = B, the number of elements in B and I must be the same.
BTW! the value n is 10.
I want the arrays y and x with 2 decimal values. Ex: 1.23
Thanks a lot.
Raúl. In an assignment A(I) = B, the number of elements in B and I must be the same.
4 件のコメント
the cyclist
2013 年 3 月 21 日
What is the size of your variable d? If it is a matrix, then it looks like the line
x(k) = sqrt(d^2+(2*y(k))^2)-d;
is trying to assign a matrix into a single element, and that will give the error you see.
Raúl
2013 年 3 月 21 日
Walter Roberson
2013 年 3 月 22 日
Are you trying to change how the number is displayed, or to assign a new value that is the old one rounded to 2 decimal digits?
Raúl
2013 年 3 月 25 日
採用された回答
その他の回答 (1 件)
How about this:
a = rand(1,10);
y ={};
n=length(a);
for k = 1:n
y{k} = sprintf('%0.2f',a(k));
end
Because sprintf returns a string, you need to put it in a cell: {}.
You could also round a like this (if you do not want strings):
a = rand(1,10);
y = round(a * 100)/100; % two decimals remain; more decimals are set to 0.
1 件のコメント
Raúl
2013 年 3 月 21 日
編集済み: Walter Roberson
2013 年 3 月 22 日
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!