File: ef230-2023-08/www/examples/webpage_create.m Download
%! Example of how to create a web page with Matlab output
%! Has functions for putting tables, text, titles, and images on the page
% University of Tennessee : Will Schleter
function main

clear all; close all; clc;
studs = 1:1:10;
scores = rand(size(studs)).*100;
figure(1);
bar(studs,scores);
title('random grading');
xlabel('student id');
ylabel('score');

fn = 'test.htm';
webpage(fn,'start','matlab web page title')
webpage(fn,'text','This is easy')
webpage(fn,'table',{'id','score'},[studs;scores]')
webpage(fn,'figure',1)
webpage(fn,'text','The end')
webpage(fn,'show')

function webpage(webfile,func,varargin)
switch func
    case 'start'
        mytitle = char(varargin(1));
        fid = fopen(webfile,'wt');
        fprintf(fid,'<html><head>\n');
        fprintf(fid,'<title>%s</title>\n',mytitle);
        fprintf(fid,'</head><body>\n');
        fprintf(fid,'<h2>%s</h2>\n',mytitle);
        fclose(fid);
    case 'show'
        web(['file:' which(webfile)],'-browser'); % use which to get the full file spec
    case 'table'
        headings = char(varargin{1});
        data = cell2mat(varargin(2));
        fid = fopen(webfile,'at');
        fprintf(fid,'<p><table border=1>\n');
        for ii=1:1:size(headings,1)
            fprintf(fid,'<th>%s</th>',headings(ii,:));
        end
        for ii=1:1:size(data,1)
            fprintf(fid,'<tr>');
            fprintf(fid,'<td>%.1f</td>',data(ii,:));
            fprintf(fid,'</tr>\n');
        end
        fprintf(fid,'</table>\n');
        fclose(fid);
    case 'figure'
        fig = cell2mat(varargin(1));
        figure(fig);
        [pathstr,name,ext,versn] = fileparts(webfile);
        imgfile = fullfile(pathstr,[ [name '_fig' num2str(gcf)] '.png' versn]);
        print('-dpng', '-r100', imgfile); % save current figure to a file
        fid = fopen(webfile,'at');
        fprintf(fid,'<p><img src="%s">\n',imgfile);% reference that file in the web page
        fclose(fid);
    case 'text'
        txt = char(varargin{1});
        fid = fopen(webfile,'at');
        fprintf(fid,'<p>%s\n',txt);
        fclose(fid);
    otherwise
        fprintf('Unknown webpage function: %s',func);
end
return