delete all the decimal digits that are 0 after the first decimal place
2 ビュー (過去 30 日間)
古いコメントを表示
Hi! I need to transform the vector V with only the first decimal. Is there an easy way to do this?
For example I am trying this way but the 9 becomes 9.0:
V = [
6.20000000000000
7.50000000000000
9
10.2000000000000
9.40000000000000];
F = {};
for ii = 1:height(V)
FF = sprintf('%.1f', V(ii));
F = [F,{FF}];
end
1 件のコメント
Dyuman Joshi
2023 年 9 月 10 日
Do you want the output to be numeric or string/char?
It would be better if you could specify what the expect output is.
採用された回答
Voss
2023 年 9 月 10 日
Using %g instead of %.1f does what you want, for this example at least.
Also, you can use compose instead of the for loop:
F = compose('%g',V);
7 件のコメント
Walter Roberson
2023 年 9 月 10 日
You are confusing how numbers are stored with how they are displayed .
6.2 exactly cannot be stored in any basic MATLAB numeric format.
MATLAB uses finite representation of numbers, and it is a mathematical truth that for any finite fixed-point representation or finite floating-point representation in any mathematical base (such as decimal -> base 10, binary -> base 2) that there are numbers that cannot be exactly represented. Base 10 (decimal) has this problem to. Suppose that you are using 10-digit numbers in base 10, and represent 1/3 -> 0.3333333333 . Now add 3 of them and you get 0.999999999 even though 3 * (1/3) should be exactly 1. So there are a lot of numbers that finite base 10 cannot represent exactly. MATLAB uses base 2, and has a different set of numbers that cannot be represented exactly, but this is not a "bug", it is a fundamental mathematical limitation of finite representation.
Rather than display the full complete decimal equivalent of each number, MATLAB's display routines show an approximation of the number. The level of detail of the approximation depend upon what setting of format you are using.
If you are using format short g then MATLAB displays up to 5 significant figures . After it has internally rounded to 5 significant figures, it removes trailing 0s from fractions:
format short g
V = [
6.20000000000000
7.50000000000000
9
10.2000000000000
9.40000000000000]
This is for display and does not affect how the value is stored. For example the third entry might display as 9 with no decimal place, but it will still be stored as a double precision number.
You can use round(V,1) to round the elements in V to the nearest representable number to rounding to one decimal place. That would affect what was stored -- but not (directly) what was displayed.
その他の回答 (1 件)
Sulaymon Eshkabilov
2023 年 9 月 10 日
Here is one slightly different option:
V = [
6.20000000000000
7.50000000000000
9
10.2000000000000
9.40000000000000];
for ii=1:numel(V)
FF{ii} = num2str(round(V(ii), 1), '%.1f');
end
FF
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!