How i can convert a number in table to 6-digit decimal?
52 ビュー (過去 30 日間)
古いコメントを表示
採用された回答
Cameron
2023 年 3 月 22 日
Do you mean 6 total digits or 6 digits after the decimal? For 6 total digits, you can do this:
T = ([1:10;pi:pi:10*pi])';
MyArray = strings(size(T));
for row = 1:size(T,1)
for col = 1:size(T,2)
MyArray(row,col) = regexprep(sprintf('%#.7g',T(row,col)),'.$','');
end
end
disp(MyArray)
For 6 digits after the decimal, you can do this:
T = ([1:10;pi:pi:10*pi])';
MyArray = strings(size(T));
for row = 1:size(T,1)
for col = 1:size(T,2)
MyArray(row,col) = sprintf('%.6f',T(row,col));
end
end
disp(MyArray)
その他の回答 (1 件)
Adam Danz
2023 年 3 月 22 日
Do you want to round your data to 6 decimal places or do you want to only display 6 decimal places?
Rounding data
There should be a good motivation to round your data since rounding reduces precision.
If the table T only contains numeric values, to round to 6 decimal places,
format long % for demo purposes; use "format default" to revert to default
T = table(randi(9,6,1),rand(6,1),rand(6,1))
T = round(T,6)
If there are non-numeric values, you must index the numeric columns,
T = table(randi(9,6,1),rand(6,1),rand(6,1),["A";"B";"C";"D";"E";"F"])
isnum = varfun(@isnumeric,T,'OutputFormat','uniform');
T(:,isnum) = round(T(:,isnum),6)
Limiting the display
One way to limit the display of all numeric values is to use the DisplayFormatOptions function (R2021a and later) or to set the format(style). However, options are limited to a predefined list of formats and numeric values that have fewer decimal places will not be padded. MATLAB does not show trailing 0s. This willl change the display of all numeric values in the command window.
The only way to show a specific number of decimal places with padded 0s is to convert the numeric values to strings (or characters or categoricals). This makes the numeric values more difficult to work with in MATLAB since they are no longer numbers. The for-loops @Cameron shared in the other answer is one way to achieve this. This method below only acts on columns of numeric data.
T = table(randi(9,6,1),rand(6,1),rand(6,1),["A";"B";"C";"D";"E";"F"])
isnum = varfun(@isnumeric,T,'OutputFormat','uniform');
T = convertvars(T,isnum,'string'); % R2018b or later
T(:,isnum) = arrayfun(@(n) {sprintf('%.6f',n)},T{:,isnum})
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!