Matlab Generate Report
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The MATLAB Report Generation skill provides a unified framework for creating structured, professional documentation directly from MATLAB and Simulink. It leverages the Report API for high-level document structure and the DOM API for granular control over formatting, tables, and images. The system supports template-based styling, custom reporter classes for branded content, and specialized tools for documenting Simulink models, including block diagrams and execution order.
What it does
- Creates PDF, Word, and HTML documents from MATLAB data.
- Supports auto-numbered figures, tables, and chapters.
- Generates technical documentation for Simulink models.
- Enables custom branded templates with headers, footers, and page borders.
- Provides a scaffolded approach for building custom reporter classes.
- Supports multipage HTML output with navigation.
When to use it
- When you need to automate the creation of technical reports from MATLAB analysis.
- When documenting Simulink models, including system I/O and execution order.
- When you require consistent, branded document styling across multiple reports.
- When you need to integrate MATLAB plots and data into professional PDF or Word documents.
Advantages
- Maintains document structure and numbering automatically.
- Separates content logic from visual styling via templates.
- Provides specialized support for complex Simulink model documentation.
- Allows for highly customized, reusable report components.
Usage examples
- “Create a basic PDF report with a title page and a chapter containing a plot.”
- The agent provides a script using mlreportgen.report.Report, TitlePage, and Figure classes to generate a PDF with auto-numbered content.
- “How do I document a Simulink model's system I/O?”
- The agent guides you to use slreportgen.report.Report and the SystemIO reporter to extract and format model I/O data.
- “How can I create a custom report template?”
- The agent instructs you to use the customizeReporter method to scaffold a custom reporter class and its associated template files.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-generate-report/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-generate-report.zip -d .agents/skills
Documentation by MathWorks
MATLAB Report Generation
Generate structured, professional reports (PDF, Word, HTML) from MATLAB data and Simulink models.
When to Use
Creating PDF, Word, or HTML reports from MATLAB data
Building reports with chapters, title pages, tables of contents
Adding auto-numbered figures and tables to documents
Creating multipage HTML reports (separate HTML files with navigation)
Documenting Simulink models with block diagrams, I/O tables, execution order
Customizing report templates (styles, colors, fonts, headers, footers)
Creating custom reporter classes with template holes and dynamic content
Building multi-reporter packages with shared company styles
Creating table variant reporters with different header colors
Including HTML content in reports
When NOT to Use
Simple file export (CSV, Excel) — use
writetable,writematrixLive Scripts as reports — use MATLAB Live Editor export
Interactive report building — use Report Explorer GUI
Web views of Simulink models — use
slreportgen.webview.*directly
API Selection
Always use the Report API (mlreportgen.report.*) as the foundation. It provides the Report container and reporters (Figure, BaseTable, FormalImage, Chapter, TitlePage, etc.) that handle auto-numbering, captions, and document structure.
Use both APIs together. Use the Report API to create the report and add content for which reporters exist. Use the DOM API (mlreportgen.dom.*) for styled paragraphs, custom tables, inline formatting, HTML inclusion, and images without captions. DOM objects append directly to Report, Chapter, or Section alongside reporters.
Critical rule: Report API reporters (Figure, BaseTable, FormalImage) can ONLY be appended to Report, Chapter, or Section objects — never to DOM objects like TableEntry. Use DOM objects inside TableEntry.
Simulink reports: Use slreportgen.report.Report (not mlreportgen.report.Report) — it extends the base with model compilation support required by SystemIO, ExecutionOrder, and other Simulink reporters.
Multipage HTML: Use mlreportgen.dom.Document with "html-multipage" type + HTMLPage objects. This is the only case where you use the DOM Document instead of the Report API Report.
Core Workflow: Standard Report
TitlePage, TableOfContents, ListOfFigures, and ListOfTables are optional — include only when the task requires them. The minimal report is just Report + content + close.
import mlreportgen.report.*
import mlreportgen.dom.*
rpt = Report("MyReport","pdf");
append(rpt,TitlePage(Title="Report Title",Author="Team")); % optional
append(rpt,TableOfContents()); % optional
append(rpt,ListOfFigures()); % optional
append(rpt,ListOfTables()); % optional
ch = Chapter("Results");
append(ch,Paragraph("Analysis complete."));
% Auto-numbered table
data = FormalTable(["ID","Value"],[1 10; 2 20]);
bt = BaseTable(data);
bt.Title = "Measured values";
append(ch,bt);
% Auto-numbered figure
fig = figure("Visible","off");
plot([1 2],[10 20]);
rptFig = Figure(fig);
rptFig.Snapshot.Caption = "Value trend";
append(ch,rptFig);
close(fig);
append(rpt,ch);
close(rpt);
rptview(rpt);Core Workflow: Simulink Report
load_system(modelName);
% MUST use slreportgen.report.Report for Simulink content
rpt = slreportgen.report.Report(outputPath,"pdf");
append(rpt,mlreportgen.report.TitlePage("Title","Model Report"));
append(rpt,mlreportgen.report.TableOfContents());
ch = mlreportgen.report.Chapter("Diagrams");
% Root diagram — direct reporter
rootDiag = slreportgen.report.Diagram(modelName);
rootDiag.Snapshot.ScaleToFit = true;
append(ch,rootDiag);
% Subsystems — finder pattern (iterator for memory efficiency)
finder = slreportgen.finder.SystemDiagramFinder(modelName);
finder.IncludeRoot = false;
finder.SortType = "alphabetical";
while finder.hasNext()
result = finder.next();
sec = mlreportgen.report.Section("Title",result.Name);
append(sec,result);
append(ch,sec);
end
append(rpt,ch);
close(rpt);
rptview(rpt);Choosing Built-In vs Custom Reporters
Before writing code, analyze requirements against built-in reporter capabilities:
List all content/format requirements — title page fields, page borders, headers/footers, branded styling
Check built-in reporters. Built-in
TitlePagehas: Title, Subtitle, Author, Publisher, PubDate, Image. Built-inChapter/Sectionprovide headings, auto-numbering, and a Content hole.If built-in reporters meet all requirements, use them directly
If any requirement is unmet, create custom reporters:
Single custom reporter — see references/custom-reporters.md
Multiple reporters sharing a visual identity — see references/report-package.md
Common triggers for custom reporters:
Title page needs fields beyond the standard set (project name, facility, contract number)
Page borders, watermarks, or custom page layout
Page headers/footers with dynamic content (per-chapter images, tickers)
Branded table variants with different header colors
MATLAB-generated logos (geometric shapes drawn with plot/patch + exportgraphics)
Do NOT force-fit requirements into built-in properties (e.g., concatenating fields into Subtitle). Create a custom reporter instead.
Do NOT build custom title pages with raw DOM elements (Paragraphs, Images appended to a Chapter). Always use customizeReporter for template-based layout and format portability.
Decision Tree: What Reference Do I Need?
| I need to... | Reference |
|---|---|
| Build a standard report with chapters, figures, tables, verification | references/report-api-patterns.md |
| Work with DOM tables, HTML inclusion, multipage HTML, Number/NumberFormat | references/dom-api-patterns.md |
| Understand template file types, locate/inspect templates | references/template-system.md |
| Look up built-in template holes, styles, page layout (pre-computed) | references/template-reference.md |
| Create a custom reporter class (customizeReporter, holes, headers) | references/custom-reporters.md |
| Build a multi-reporter package with shared styles and buildTemplates | references/report-package.md |
| Generate Simulink model reports (finders, orientation, centering) | references/simulink-report.md |
| Look up all Simulink finders and reporters | references/finders-and-reporters.md |
| Iterate struct arrays into chapters with custom reporters | references/data-driven-report-pattern.md |
| Edit template styles (colors, fonts, headers, footers, TOC) | references/template-system.md |
Key Functions
| Class | Purpose | Package |
|---|---|---|
Report | Top-level report container | mlreportgen.report |
TitlePage | Title page with title, subtitle, author | mlreportgen.report |
TableOfContents | Auto-generated TOC | mlreportgen.report |
Chapter / Section | Document structure | mlreportgen.report |
Figure | Auto-numbered figure from MATLAB figure | mlreportgen.report |
FormalImage | Auto-numbered image from file with caption | mlreportgen.report |
BaseTable | Auto-numbered table wrapper (pass FormalTable) | mlreportgen.report |
FormalTable | Table with header/body/footer from cell arrays | mlreportgen.dom |
Template (3-arg) | Edit templates: Template(out,fmt,src) | mlreportgen.dom |
HTMLFile / HTML | Include HTML content in any output format | mlreportgen.dom |
HTMLPage | Page in multipage HTML document (R2024a+) | mlreportgen.dom |
Number | Numeric DOM object (use with NumberFormat) | mlreportgen.dom |
TemplateHole | Placeholder filled at report time | mlreportgen.dom |
Page / NumPages | Page number / total pages | mlreportgen.dom |
*.customizeReporter | Scaffold custom reporter + templates | mlreportgen.report |
getStyle / replaceStyle | Modify template styles | mlreportgen.dom |
slreportgen.report.Report | Report container for Simulink content | slreportgen.report |
slreportgen.report.Diagram | Diagram snapshot of a system | slreportgen.report |
slreportgen.finder.SystemDiagramFinder | Find system/subsystem diagrams | slreportgen.finder |
slreportgen.report.SystemIO | Report inputs/outputs (requires compilation) | slreportgen.report |
slreportgen.report.ExecutionOrder | Report block execution order | slreportgen.report |
slreportgen.report.LookupTable | Report lookup table data + plot | slreportgen.report |
rptview | Display report (updates DOCX fields) | function |
docview | Process Word documents (update fields, convert) | function |
Common Mistakes
| Mistake | Correct Approach |
|---|---|
Using mlreportgen.dom.Document as report container | Use mlreportgen.report.Report. Exception: multipage HTML requires Document with "html-multipage" |
Using mlreportgen.report.Report for Simulink content | Use slreportgen.report.Report — needed for model compilation |
Using Report with "html" for multipage output | Use mlreportgen.dom.Document with "html-multipage" + HTMLPage objects |
| Appending reporters to DOM objects (Paragraph, TableEntry) | Reporters can ONLY go in Report, Chapter, or Section. Use DOM objects inside TableEntry |
Putting raw doubles in FormalTable cells | Use Number with NumberFormat in Style: n = Number(42); n.Style = {NumberFormat("%.0f")}. Put n directly in cell arrays. See references/dom-api-patterns.md § Number and NumberFormat |
NumberFormat("$%.0f") or NumberFormat("%,.0f") | Only standard sprintf specifiers work (no $, no %,, no %d). For currency/units, wrap Number in Paragraph and prepend/append Text |
| Customizing only "default"/"even" page headers | Customize ALL page types: "first", "default", "even" — but differentiate content (see below) |
| Putting StyleRef (chapter title) in the first-page header | First page already displays the chapter heading — omit StyleRef from "first" header. Use it only in "default"/"even" for wayfinding |
Opening DOCX with winopen/open/start | Use rptview(rpt) or docview(file,"updatefields") — triggers field update |
Using ColSpec/ColSpecGroup for widths | Use TableColSpecGroup + TableColSpec with Width in Style |
Setting widths without ResizeToFitContents(false) | Add ResizeToFitContents(false) to table Style; set absolute ft.Width (not "100%") |
TemplateParagraphStyle.Formats = {Bold(true)} | Use array: Formats = [Bold(true),FontSize("12pt")] |
Template(path,"pdf") to edit existing template | 2-arg creates blank. Use 3-arg: Template(out,"pdf",src) |
| Same path for source and output in Template constructor | OPC cannot read/write simultaneously. Use different paths, then movefile |
Setting PDFPageLayout.PageSize.Orientation without rotate() | Call rotate(pl) — swaps Width/Height AND sets Orientation |
Using DOCXPageLayout without explicit Height and Width | DOCX does not auto-swap — set both explicitly |
Page numbers resetting after PDFPageLayout | Set pl.FirstPageNumber = '' (empty string) to continue numbering |
| Wrapping reporter in Paragraph to center it | Customize the reporter's template style via Template API |
Using RawText(html) for HTML in PDF | Use HTMLFile(path) or HTML(string) — works for any format |
Using Group in a Table cell array | Use nested cell arrays: Table({{img,caption},desc}) |
Passing MATLAB table() to BaseTable | Pass FormalTable(headers,body) — avoids MATLABTable wrapper |
e.Style = {BackgroundColor("yellow")} (overwrites existing styles) | Append: e.Style = [e.Style, {BackgroundColor("yellow")}] — preserves inherited styles |
Force-fitting fields into TitlePage.Subtitle | Create a custom title page reporter via customizeReporter |
| Writing custom reporter class from scratch | Use customizeReporter to scaffold — creates required binary templates |
Writing classdef before running customizeReporter | Scaffolding overwrites classdef files. Scaffold first, then edit |
Unqualified TitlePage.getClassFolder() in package | Use fully-qualified: mypkg.TitlePage.getClassFolder() |
getStyle(ss,name,type) for PDF/HTML | Type arg returns []. Use getStyle(ss,name) without type |
OuterMargin("12pt","6pt","0","0") for vertical spacing | Args are (left,right,top,bottom) — NOT CSS order. Use OuterMargin("0","0","12pt","6pt") for top/bottom spacing |
Using TemplateCharacterStyle | Does not exist. Use TemplateTextStyle for character/inline styles in PDF/HTML |
Unzipping .pdftx/.htmtx/.dotx to edit with fileread/regexprep | ALWAYS use DOM Template API — Template(out,fmt,src) + open + modify objects + close. Raw edits bypass framework validation |
find_system + DiagramFinder for discovery | Use SystemDiagramFinder with filter properties |
Diagram(result.Path) on ChartDiagramFinder results | Use getReporter(result) — chart paths are invalid for Diagram constructor |
find() + for loop on finders | Always use iterator: while finder.hasNext() / result = finder.next() |
BlockFinder with SearchDepth=inf expecting referenced models | BlockFinder does NOT traverse Model References. Use SystemDiagramFinder (IncludeReferencedModels=true) + per-system BlockFinder (SearchDepth=1) |
ExecutionOrder on virtual subsystem | Check get_param(obj,'IsSubsystemVirtual') first |
ExecutionOrder/SystemIO on Simulink Functions | Guard with slreportgen.utils.isSimulinkFunction(result.Object) |
Conventions
Always
close(rpt)after appending all content — generates the output fileAlways
rptviewordocviewto open DOCX — neverwinopenoropenUse
figure("Visible","off")for plots destined for reportsUse
exportgraphics(notprint) when saving figures to filesOne Chapter = one numbering scope — figures/tables numbered Chapter-Sequence (e.g., "Figure 2-1")
BaseTablewrapsFormalTable— passFormalTable(headers,body), not a MATLABtable()Cell-level styling: Use
entry(t,row,col)after construction, not duringTemplate styles use
[]arrays; inline.Styleproperties use{}Reporters in
@ClassNamedirectories — each needs its ownresources/templates/Scaffold ALL reporters before editing ANY —
customizeReportercreates binary templates + overwrites classdefFix unqualified class names after scaffolding — use package-qualified names
Customize all output formats — PDF/Word/HTML templates are independent
Simulink: Always
slreportgen.report.Report; alwaysDiagram.Snapshot.ScaleToFit = trueSimulink finders: Use
.Objecthandle (not path string) forget_param; useresult.Namefor titlesJSON is single source of truth for multi-reporter packages — never hardcode style values
Viewing and Processing Reports
rptview(rpt); % Open in system viewer (updates DOCX fields)
rptview("MyReport.docx","pdf"); % Convert DOCX to PDF via Word
docview("Report.docx","updatefields","closedoc","closeapp"); % Update without displayVerification: Running without error does NOT confirm correctness. After close(rpt):
Check
isfile(rpt.OutputPath)anddir(rpt.OutputPath).bytes > 1000For PDF: call
open(rpt), then setrpt.Document.RetainFO = truebefore appending content, search*_FO/*.fofilesFor DOCX: unzip and search
word/document.xmlAssert expected titles, headings, captions appear in output
See references/report-api-patterns.md for full verification patterns.
Required Toolbox
MATLAB Report Generator (verify with mcp__matlab__detect_matlab_toolboxes). Simulink Report Generator additionally required for Simulink model reports.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md17.1 KiB
- manifest.yaml598 B
- references/custom-reporters.md39.1 KiB
- references/data-driven-report-pattern.md13.1 KiB
- references/dom-api-patterns.md31.0 KiB
- references/finders-and-reporters.md13.1 KiB
- references/report-api-patterns.md7.2 KiB
- references/report-package.md15.8 KiB
- references/simulink-report.md19.9 KiB
- references/template-reference.md38.1 KiB
- references/template-system.md30.9 KiB
references/data-driven-report-pattern.md
Data-Driven Report Pattern
Generate reports where a collection of data items (companies, test specimens, sites, etc.) produces one chapter per item, each with custom reporters and per-item template hole content.
When to Use
Struct array or table input where each row/element becomes a chapter
Custom reporters (TitlePage, Chapter) with per-item properties (logos, tickers, names)
Sections that may be present or missing depending on available data
Need graceful handling of incomplete input without crashing
Architecture
+mypkg/
├── @TitlePage/TitlePage.m % Custom: firm logo hole, report metadata
├── @Chapter/Chapter.m % Custom: per-item page headers (logo, ticker, StyleRef)
├── +reporters/ % Section-level content builders
│ ├── SummaryReporter.m
│ ├── FinancialReporter.m
│ └── GenericSection.m
└── +helpers/
├── buildChapter.m % Orchestrates sections into a chapter
└── dataNotAvailable.m % Graceful missing-data placeholderEntry point: A function or script that accepts the data array, creates the Report, and loops.
Core Pattern
function rpt = generateReport(items,options)
%generateReport Create a multi-item report from a struct array.
arguments
items (1,:) struct
options.Format (1,1) string = "pdf"
options.OutputPath (1,1) string = fullfile(pwd,"output","report")
options.FirmLogo (1,1) string = ""
end
import mlreportgen.report.*
import mlreportgen.dom.*
rpt = Report(options.OutputPath,options.Format);
open(rpt);
% --- Title Page (custom reporter, NOT built-in) ---
tp = mypkg.TitlePage();
tp.Title = "Portfolio Report";
tp.Author = "Research Team";
if options.FirmLogo ~= "" && isfile(options.FirmLogo)
tp.FirmLogo = options.FirmLogo;
end
append(rpt,tp);
append(rpt,TableOfContents());
% --- One chapter per item ---
for i = 1:numel(items)
ch = mypkg.Chapter(items(i).Name);
% Per-chapter properties fill template holes (page headers, etc.)
ch.Ticker = items(i).Ticker;
if isfield(items(i),"LogoPath") && isfile(items(i).LogoPath)
ch.CompanyLogo = items(i).LogoPath;
end
% Delegate section assembly to a helper
mypkg.helpers.buildChapter(ch,items(i));
append(rpt,ch);
end
close(rpt);
endCritical Rules
1. Always instantiate YOUR custom reporter — never the built-in parent
% WRONG — uses built-in TitlePage, your template customizations are ignored
tp = mlreportgen.report.TitlePage();
% CORRECT — uses your custom TitlePage with FirmLogoContent hole
tp = mypkg.TitlePage();Every custom reporter you scaffold via customizeReporter MUST be instantiated by its package-qualified name. If you instantiate the parent class, your custom templates (with their holes, page headers, borders) are never loaded.
2. Per-item properties fill template holes automatically
The custom Chapter reporter has properties like Ticker, CompanyLogo that match template holes in the page header. When getImpl runs, it fills these holes from the property values. No override needed — just set the property before appending:
ch = mypkg.Chapter("TechVision Corp");
ch.Ticker = "TVCO";
ch.CompanyLogo = "data/tvco_logo.png";
% Template holes "Ticker" and "CompanyLogo" are filled automatically3. Graceful missing-field handling
Never let a missing field crash the report. Use a helper that checks and provides a fallback:
function content = safeField(item,fieldName,fallback)
%safeField Return field value or fallback if missing/empty.
arguments
item (1,1) struct
fieldName (1,1) string
fallback = []
end
if isfield(item,fieldName) && ~isempty(item.(fieldName))
content = item.(fieldName);
else
content = fallback;
end
endFor sections: skip the section entirely if data is missing, or insert a "Data not available" placeholder:
function addSectionIfPresent(ch,item,fieldName,sectionTitle)
import mlreportgen.dom.*
data = safeField(item,fieldName);
if isempty(data)
return % Omit section entirely
end
sec = mlreportgen.report.Section(sectionTitle);
% ... build section content from data ...
append(ch,sec);
endAlways use isempty() — never == "" — to test for missing content. Struct fields may be strings, cell arrays, structs, or numeric arrays. The == operator fails on cell arrays with "Cell must be a cell array of character vectors."
4. Chapter builder orchestrates sections
Keep the main loop thin. A helper function knows the section order and delegates to section reporters:
function buildChapter(ch,item)
%buildChapter Assemble all sections into a chapter from item data.
import mlreportgen.report.*
% Section order is defined here — easy to add/remove/reorder
addExecutiveSummary(ch,item);
addSectionIfPresent(ch,item,"CompanyUpdate","Company Update");
addSectionIfPresent(ch,item,"InvestmentThesis","Investment Thesis");
addSectionIfPresent(ch,item,"BusinessOverview","Business Overview");
addFinancials(ch,item);
addSectionIfPresent(ch,item,"Risks","Risks");
addSectionIfPresent(ch,item,"Disclaimers","Disclaimers");
end5. Section reporters encapsulate formatting logic
Each section reporter handles one content domain. It takes raw data (struct fields, tables, cell arrays) and produces formatted DOM content:
function addFinancials(ch,item)
import mlreportgen.report.*
import mlreportgen.dom.*
if ~isfield(item,"FinancialTable") || isempty(item.FinancialTable)
return
end
sec = Section("Financial Summary");
% Convert MATLAB table to FormalTable (never pass table() to BaseTable)
t = item.FinancialTable;
header = t.Properties.VariableNames;
body = table2cell(t);
ft = FormalTable(header,body);
ft.Width = "6.5in";
ft.Style = [ft.Style {ResizeToFitContents(false)}];
ft.Header.Style = {Bold(true),BackgroundColor("#1B3A5C"),Color("white")};
bt = BaseTable(ft);
bt.Title = item.Name + " — Key Financials";
append(sec,bt);
append(ch,sec);
endInput Schema Pattern
Define expected fields clearly. Use a validation function that normalizes input:
function items = validateInput(raw)
%validateInput Normalize input to struct array with expected fields.
requiredFields = ["Name","Ticker"];
optionalFields = ["Sector","LogoPath","Recommendation","CurrentPrice",...
"TargetPrice","CompanyUpdate","InvestmentThesis","BusinessOverview",...
"FinancialTable","Risks","Disclaimers"];
if istable(raw)
raw = table2struct(raw);
end
for i = 1:numel(raw)
for f = requiredFields
assert(isfield(raw(i),f) && ~isempty(raw(i).(f)),...
"Item %d missing required field: %s",i,f);
end
for f = optionalFields
if ~isfield(raw(i),f)
raw(i).(f) = [];
end
end
end
items = raw;
endCommon Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
Instantiating mlreportgen.report.TitlePage instead of mypkg.TitlePage | Built-in template is loaded — custom holes, page borders, and layout are ignored | Always use the package-qualified custom class name |
Checking item.Field without isfield guard | Errors on structs where the field doesn't exist | Use isfield(item,fieldName) before accessing |
| Putting all section logic in the main loop | Produces an unreadable 500-line function that's hard to extend | Delegate to buildChapter → per-section helpers |
Passing table() to BaseTable | MATLABTable wrapper adds unwanted formatting (quotes, command-window style) | Convert to FormalTable(headers,body) first |
Setting reporter properties AFTER append(rpt,ch) | getImpl runs during append — properties must be set before | Set all properties, THEN append |
| Assuming all items have the same fields | Real data has gaps — some companies lack forecasts, logos, or analyst notes | Guard every field access; skip or placeholder missing sections |
Per-Chapter Page Header: Complete End-to-End Pattern
When each chapter needs distinct page header content (company logo, ticker, etc.), the full chain is:
Reporter class — typed properties matching template hole IDs
Template — holes in the page header (PDF and DOCX; HTML has no page headers)
Generation loop — construct Image objects from file paths, set properties BEFORE
append
Reporter Class (Properties)
classdef Chapter < mlreportgen.report.Chapter
% File: +mypkg/@Chapter/Chapter.m
properties
% These property names MUST exactly match hole IDs in the template
HeaderLogo {mustBeLogoValue} = [] % Fills "HeaderLogo" hole ([], Image, or path)
HeaderTicker string = "" % Fills "HeaderTicker" hole
end
methods
function obj = Chapter(varargin)
obj = [email protected](varargin{:});
end
function img = getHeaderLogo(obj)
%getHeaderLogo Return Image object for the HeaderLogo hole.
if isempty(obj.HeaderLogo)
img = [];
elseif isa(obj.HeaderLogo,"mlreportgen.dom.Image")
img = obj.HeaderLogo;
else
img = mlreportgen.dom.Image(string(obj.HeaderLogo));
img.Width = "0.4in";
img.Height = "0.4in";
end
end
end
% ... template infrastructure methods (from customizeReporter) ...
end
% In a separate methods block or as a local function in the classdef file:
function mustBeLogoValue(v)
if isempty(v), return; end
if isa(v,"mlreportgen.dom.Image"), return; end
if isstring(v) || ischar(v), return; end
error("HeaderLogo must be [], an Image object, or a file path string.");
endGeneration Loop (Constructing and Assigning)
for i = 1:numel(items)
ch = mypkg.Chapter(items(i).Name); % Title = company name only (no ticker)
% Ticker: simple string assignment
ch.HeaderTicker = items(i).Ticker;
% Logo: assign path string OR Image object — getHeaderLogo handles both
if isfield(items(i),"LogoPath") && ~isempty(items(i).LogoPath) ...
&& isfile(items(i).LogoPath)
ch.HeaderLogo = items(i).LogoPath; % string path (getHeaderLogo wraps it)
end
% If no logo: property stays [], hole renders empty (graceful)
% Build chapter content...
mypkg.helpers.buildChapter(ch,items(i));
% Properties MUST be set before append — getImpl runs during append
append(rpt,ch);
endCritical Rules for Header Holes
| Rule | Why |
|---|---|
| Property name = hole ID (exact match, case-sensitive) | Framework uses name matching to fill holes |
Set properties BEFORE append(rpt,ch) | getImpl executes during append — later assignments are ignored |
| Image properties need explicit Width/Height | Without sizing, images render at natural size (often too large for headers) |
| Holes inside a Paragraph are inline | Property must be inline content (Image, Text) — NOT a Paragraph or Table |
| Block-level holes accept any content | If the hole is directly in the header (not inside a Paragraph), Paragraph/Table are fine |
| String properties fill as Text | A string property becomes a Text node in the hole — styled by the hole's DefaultStyleName |
| Empty properties leave holes unfilled | [] or "" → hole renders nothing (graceful degradation) |
Use untyped = [] for optional Image properties | Typed mlreportgen.dom.Image fails with empty 0x0 array; use {mustBeLogoValue} = [] with a get<HoleId>() accessor |
Debugging Header Holes That Don't Render
If content doesn't appear in the page header:
Verify property name matches hole ID exactly — case-sensitive, no extra spaces
Check the property is set before
append— add a breakpoint orfprintfbeforeappend(rpt,ch)Verify the hole exists in BOTH PDF and DOCX templates — a hole in PDF but not DOCX means DOCX output has no content
Check inline vs block context — a hole inside a
<p>in the template is inline; returning aParagraphto an inline hole errors silently or shows nothingRe-scaffold if templates may be corrupted — run
customizeReporteragain to get fresh templates, then re-apply your edits
Extending the Pattern
Adding a new section: Create a helper function, add one line to buildChapter. No other code changes needed.
Adding a new per-chapter header element: Add a property to the custom Chapter class, add a matching template hole to the page header template (all formats), set the property in the main loop.
Supporting a new output format: Custom reporters with properly scaffolded templates (customizeReporter creates PDF, DOCX, and HTML templates) already support all formats. Just change options.Format.
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/reporting-and-database-access/matlab-generate-report · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-generate-report.zip