How can I convert a numeric array into a table and format the data so that each number has 2 decimals in MATLAB?

33 views (last 30 days)
I'm new to the Table data type, and am trying to get the numeric values in the table to all have the same number of decimals. My data starts as a matrix. I round it to two decimals, then convert it to cell, then convert the cell to table. The problem is that when a value is an integer, it doesn't print the decimals (i.e."1" instead of "1.00"). I tried the "sprintf" command but can't get that output into the table.
 
Any suggestions you have would be appreciated. Thanks!

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 14 Apr 2014
The variable editor in MATLAB will not display zeros after the decimal points for round numbers in a table when the table contains numeric data. If you want to display a fixed number of decimals for numbers (like in Microsoft Excel), you would have to convert the numeric data to strings and format the strings using "sprintf."
The following piece of code converts a numeric array to a table of strings, each element being forced to have 2 digits after the decimal point using "sprintf". The "cellfun" function is used with an anonymous function called "fun" to apply the number-to-string conversion to each cell in the cell array.
% Generate some data
M = 100*rand(25,10);
% Set some test values to be integer
M(:,1) = round(M(:,1));
% Round it to two decimals
M = round(M*100)/100;
% Convert to a cell array of strings
C = num2cell(M);
% Convert the cells to strings with 2 decimals
fun = @(x) sprintf('%0.2f', x);
D = cellfun(fun, C, 'UniformOutput',0);
% Convert to a table
T = cell2table(D);

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!