exponenta event banner

Создание генератора отчетов

В этом примере показано, как создать простой отчет, объясняющий и иллюстрирующий магические квадраты - матрицы, столбцы, строки и диагонали которых складываются в одно и то же число. Посмотрите magic.

Примечание

Полный код примера включается после пошаговых инструкций.

  1. Импортируйте базовые классы.

    Чтобы исключить необходимость использования полных имен объектов Report и DOM API, используйте эти инструкции. Например, вместо использования mlreportgen.report.Report, вы можете использовать Report.

    import mlreportgen.report.* 
    import mlreportgen.dom.* 
  2. Создание объекта отчета.

    Создайте объект отчета. Использовать 'magic' в качестве имени файла и 'html' как тип отчета.

    rpt = Report('magic','html'); 

    Сведения о настройке свойств, применяемых ко всему отчету, см. в разделе mlreportgen.report.Report.

  3. Добавление титульной страницы.

    Создайте титульную страницу и укажите ее заголовок, подзаголовок и автора. Затем добавьте к отчету титульную страницу.

    tp = TitlePage; 
    tp.Title = 'Magic Squares'; 
    tp.Subtitle = 'Columns, Rows, Diagonals: All Equal Sums'; 
    tp.Author = 'Albrecht Durer'; 
    append(rpt,tp); 

    Title page with the title "Magic Squares", subtitle "Columns, Rows, Diagonals: All Equal Sums", author "Albrecht Durer", and the date

    Дополнительные свойства страницы заголовка см. в разделе mlreportgen.report.TitlePage.

  4. Добавление оглавления.

    Добавьте в отчет объект оглавления по умолчанию.

    append(rpt,TableOfContents); 
    

    Table of contents that lists three chapters: "Introduction", "10 by 10 Magic Square", and "25 by 25 magic square"

    Сведения о настройке оглавления см. в разделе mlreportgen.report.TableOfContents.

  5. Добавьте главу и разделы главы.

    Создайте объект главы для введения и укажите заголовок главы. Добавьте раздел, добавьте абзац в этот раздел и добавьте этот раздел в главу. Создайте другой раздел и добавьте к нему абзац.

    ch1 = Chapter; 
    ch1.Title = 'Introduction'; 
    sec1 = Section; 
    sec1.Title = 'What is a Magic Square?'; 
    para = Paragraph(['A magic square is an N-by-N matrix '... 
    'constructed from the integers 1 through N^2 '... 
    'with equal row, column, and diagonal sums.']); 
    append(sec1,para) 
    append(ch1,sec1) 
    sec2 = Section; 
    sec2.Title = 'Albrecht Durer and the Magic Square'; 
    para = Paragraph([ ... 
    'The German artist Albrecht Durer (1471-1528) created '... 
    'many woodcuts and prints with religious and '... 
    'scientific symbolism. One of his most famous works, '... 
    'Melancholia I, explores the depressed state of mind '... 
    'which opposes inspiration and expression. '... 
    'Renaissance astrologers believed that the Jupiter '... 
    'magic square (shown in the upper right portion of '... 
    'the image) could aid in the cure of melancholy. The '... 
    'engraving''s date (1514) can be found in the '... 
    'lower row of numbers in the square.']); 
    append(sec2,para) 
    append(ch1,sec2) 

    Chapter one with two sections, "What is a Magic Square" and "Albrecht Durer and the Magic Square"

    Сведения о настройке глав и разделов см. в разделе mlreportgen.report.Chapter и mlreportgen.report.Section соответственно.

  6. Добавьте фигуру.

    Создание изображения Дюрера в окне фигуры. Создайте изображение на рисунке MATLAB. Добавьте рисунок во второй раздел вводной главы, а затем добавьте главу в отчет.

    durerImage=load(which('durer.mat'),'-mat'); 
    figure('Units','Pixels','Position',... 
    [200 200 size(durerImage.X,2)*.5 ... 
    size(durerImage.X,1)*.5 ]); 
    image(durerImage.X); 
    colormap(durerImage.map); 
    axis('image'); 
    set(gca,'Xtick',[],'Ytick',[],... 
    'Units','normal','Position',[0 0 1 1]); 
    append(sec2,Figure) 
    append(rpt,ch1) 
    close gcf 

    Engraving, "Melancholia I" by Albrecht Durer

    Дополнительные сведения о рисунках см. в разделе mlreportgen.report.Figure. Дополнительные сведения об изображениях см. в разделе mlreportgen.report.FormalImage.

  7. Добавление таблицы.

    Добавьте другой объект главы и укажите его название. Укажите код MATLAB для создания магического квадрата 10 на 10. Добавьте результаты в таблицу и задайте следующие свойства таблицы:

    • Разделители строк и столбцов

    • Граница таблицы

    • Выравнивание записей таблицы

    Затем добавьте таблицу к главе и главу к отчету.

    ch2 = Chapter(); 
    ch2.Title = sprintf('10 x 10 Magic Square'); 
    
    square = magic(10); 
    tbl = Table(square); 
    
    tbl.Style = {... 
        RowSep('solid','black','1px'),... 
        ColSep('solid','black','1px'),}; 
    tbl.Border = 'double'; 
    tbl.TableEntriesStyle = {HAlign('center')}; 
    
    append(ch2,tbl); 
    append(rpt,ch2); 
    

    Chapter 2 has the title 10 by 10 Magic Square and contains a bordered table containing the magic square.

    Дополнительные сведения о таблицах см. в разделе mlreportgen.dom.Table.

  8. Добавьте рисунок MATLAB в главу.

    Добавьте другой объект главы и укажите его название. Укажите код MATLAB для создания магического квадрата 25 на 25 и закодированной цветом фигуры магического квадрата. Затем создайте объект фигуры и задайте его высоту, ширину и заголовок. Добавьте рисунок к главе и главу к отчету.

    ch3 = Chapter(); 
    ch3.Title = sprintf('25 x 25 Magic Square'); 
    
    square = magic(25); 
    clf; 
    imagesc(square) 
    set(gca,'Ydir','normal')
    axis equal 
    axis tight 
    
    fig = Figure(gcf); 
    fig.Snapshot.Height = '4in'; 
    fig.Snapshot.Width = '6in'; 
    fig.Snapshot.Caption = sprintf('25 x 25 Magic Square'); 
    
    append(ch3,fig); 
    append(rpt,ch3); 
    delete(gcf) 
    

    Chapter 3 has the title 25 by 25 Magic Square and contains a color-coded figure of the magic square.

    Дополнительные сведения о рисунках см. в разделе mlreportgen.report.Figure.

  9. Закройте и запустите отчет.

    close(rpt)
    rptview(rpt)

Полный код:

import mlreportgen.report.* 
import mlreportgen.dom.* 
rpt = Report('magic','html'); 

tp = TitlePage; 
tp.Title = 'Magic Squares'; 
tp.Subtitle = 'Columns, Rows, Diagonals: All Equal Sums'; 
tp.Author = 'Albrecht Durer'; 
append(rpt,tp); 
append(rpt,TableOfContents); 

ch1 = Chapter; 
ch1.Title = 'Introduction'; 
sec1 = Section; 
sec1.Title = 'What is a Magic Square?'; 
para = Paragraph(['A magic square is an N-by-N matrix '... 
'constructed from the integers 1 through N^2 '... 
'with equal row, column, and diagonal sums.']); 
append(sec1,para) 
append(ch1,sec1) 

sec2=Section; 
sec2.Title = 'Albrecht Durer and the Magic Square'; 
para = Paragraph([ ... 
'The German artist Albrecht Durer (1471-1528) created '... 
'many woodcuts and prints with religious and '... 
'scientific symbolism. One of his most famous works, '... 
'Melancholia I, explores the depressed state of mind '... 
'which opposes inspiration and expression. '... 
'Renaissance astrologers believed that the Jupiter '... 
'magic square (shown in the upper right portion of '... 
'the image) could aid in the cure of melancholy. The '... 
'engraving''s date (1514) can be found in the '... 
'lower row of numbers in the square.']); 
append(sec2,para) 
append(ch1,sec2) 

durerImage=load(which('durer.mat'),'-mat'); 
figure('Units','Pixels','Position',... 
[200 200 size(durerImage.X,2)*.5 ... 
size(durerImage.X,1)*.5 ]); 
image(durerImage.X); 
colormap(durerImage.map); 
axis('image'); 
set(gca,'Xtick',[],'Ytick',[],... 
'Units','normal','Position',[0 0 1 1]); 
append(sec2,Figure) 
append(rpt,ch1) 
close gcf 

ch2 = Chapter(); 
ch2.Title = sprintf('10 x 10 Magic Square'); 
square = magic(10); 
tbl = Table(square); 
tbl.Style = {... 
RowSep('solid','black','1px'),... 
ColSep('solid','black','1px'),}; 
tbl.Border = 'double'; 
tbl.TableEntriesStyle = {HAlign('center')}; 
append(ch2,tbl); 
append(rpt,ch2); 

ch3 = Chapter(); 
ch3.Title = sprintf('25 x 25 Magic Square'); 
square = magic(25); 
clf; 
imagesc(square) 
set(gca,'Ydir','normal') 
axis equal 
axis tight 
fig = Figure(gcf); 
fig.Snapshot.Height = '4in'; 
fig.Snapshot.Width = '6in'; 
fig.Snapshot.Caption = sprintf('25 x 25 Magic Square'); 
append(ch3,fig); 
append(rpt,ch3); 

delete(gcf) 
close(rpt)
rptview(rpt)

См. также