This example shows how to format numbers in a table that is generated by a report generation program. The example creates a table of uniformly distributed random numbers that have a precision of 3 digits after the decimal point. Before the table is created, the numbers are formatted in MATLAB® by using sprintf
.
Generate a 4-by-4 array of random numbers. Initialize the random number generator using a seed of 1
, so that each time the example runs, rand
produces the same numbers.
format long rng('default'); rng(1); randNumbers = rand(4)
randNumbers = 4×4
0.417022004702574 0.146755890817113 0.396767474230670 0.204452249731517
0.720324493442158 0.092338594768798 0.538816734003357 0.878117436390945
0.000114374817345 0.186260211377671 0.419194514403295 0.027387593197926
0.302332572631840 0.345560727043048 0.685219500396759 0.670467510178402
The numbers display with a precision of 15 digits after the decimal point.
Format the numbers into strings by using sprintf
. Specify a format for a fixed-point number with three digits after the decimal point. Use arrayfun
to apply sprintf
to each number in the array randNumbers
.
formattedNumbers = arrayfun(@ (n) sprintf("%1.3f", n),randNumbers)
formattedNumbers = 4×4 string
"0.417" "0.147" "0.397" "0.204"
"0.720" "0.092" "0.539" "0.878"
"0.000" "0.186" "0.419" "0.027"
"0.302" "0.346" "0.685" "0.670"
Import the DOM package so that you do not have to use long, fully-qualified class names.
import mlreportgen.dom.*
Create a PDF document. To create a Microsoft® Word, HTML, or single-file HTML document, change 'pdf'
to 'docx'
, 'html'
, or 'html-file'
, respectively.
d = Document('RandomNumbers','pdf');
Create a table from the array of formatted random numbers.
t = Table(formattedNumbers);
Specify the table border and column and row separators. Center the table entries in the table cells.
t.Style = {Width('100%'),... Border('solid'),... ColSep('solid'),... RowSep('solid')}; t.TableEntriesHAlign = 'center';
Append the table to the document. Close and view the document.
append(d,t); close(d); rptview(d);