Excluding 0.5 from rounding
古いコメントを表示
How can I exclude the 0.5 fraction from rounding such that the fractions less than or greater than 0.5 are only to be rounded?
採用された回答
その他の回答 (1 件)
Max Heimann
2022 年 1 月 13 日
編集済み: Max Heimann
2022 年 1 月 13 日
if mod(x,1) ~= 0.5
x = round(x)
end
3 件のコメント
John D'Errico
2022 年 1 月 13 日
Good idea. But while that would work for scalar x, it is not vectorized, and it will fail for vectors and arrays.
Max Heimann
2022 年 1 月 13 日
編集済み: Max Heimann
2022 年 1 月 13 日
How about this for vectors and matrices:
% Matrix with test values
x = [0 -4.5 -4.4; 3.3 0.5 1];
% Code
indices = mod(x,1) ~= 0.5;
x(indices) = round(x(indices))
John D'Errico
2022 年 1 月 13 日
Yes. That will work. And since 0.5 is exactly representable in floating point arithmetic as a double, the exact test for equality is sufficient.
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!