Mostrando las entradas con la etiqueta GUI. Mostrar todas las entradas
Mostrando las entradas con la etiqueta GUI. Mostrar todas las entradas

sábado, 19 de diciembre de 2015

Exportar datos de una uitable MATLAB a una tabla en archivo HTML: table2html.


La función table2html que se anexa a continuación permite exportar los datos contenidos en una uitable MATLAB a una tabla contenida en un archivo HTML. La utilidad puede ser en aquellos casos donde se requiera elaborar reportes con datos de salida contenidos en una uitable, evidentemente la opción "Publish" de MATLAB permite elaborar un reporte de cualquier script, pero incluye solamente capturas de los objetos gráficos. Esta función se puede adaptar para que en lugar de devolver un archivo HTML completo, solamente devuelva el código HTML de la tabla e incrustar esto posteriormente en un reporte HTML creado de manera independiente.

function table2html(hTab,filename,opts)
% TABLE2HTML(hTab,filename)
%
%   hTab       - Handle de la uitable a "exportar"
%   filename   - Nombre del archivo de salida (*.html)
%   opts       - Estructura de opciones adicionales (Veáse Opciones)
%
% Exporta una uitable como tabla en un archivo en formato HTML
%
% EJEMPLO:
%
%       f = figure();
%       hTab = uitable(f,'Data',rand(10));
%       table2html(hTab,'miejemplo.html');
%
%
% OPCIONES (OPTS)
%    
%      PageTitle   -  Título de la página web
%      TableTitle  -  Título de la tabla
%      BgColor     -  Color de fondo de la tabla
%      FontName    -  Tipo de fuente utilizada
%      BorderWidth -  Ancho del borde de la tabla
%     
% EJEMPLO CON OPCIONES:
%
%       f = figure();
%       opts.PageTitle = 'Ejemplo';
%       opts.TableTitle = 'Mi tabla';
%       opts.BgColor = '#00FF00';
%       opts.FontName = 'Arial';
%       opts.BorderWidth = '3';
%       hTab = uitable(f,'Data',rand(10));
%       table2html(hTab,'miejemplo.html',opts);
%             
%
%    -------------------------------
%       Ver. 0.0.1  ||  25/10/2014
%           Jorge De Los Santos
%        delossantosmfq@gmail.com
%        http://labdls.blogspot.mx
%              MIT License
%    -------------------------------

if nargin < 1
    % En caso de no especificarse argumentos se "busca" un elemento del
    % tipo uitable y se asigna como archivo de salida a html/utitled.html
    hTab = findobj('type','uitable');
    if ~isempty(hTab)
        filename = 'html/untitled.html';
    else
        error('No existe elemento uitable disponible');
    end
end

if ~strcmp(get(hTab,'type'),'uitable')
    % Verificando que la referencia sea tipo "uitable"
    error('La referencia debe ser de tipo uitable');
end

% ========================== OPCIONES ===================================
fields_opts = {'PageTitle',   'Sin título',;
               'TableTitle',  '<b>Tabla 1</b>';
               'BgColor',     '#F0F0F0';
               'FontName',    'DejaVu Sans Mono';
               'BorderWidth', '2';
               'FontColor',   '#0000F0'};
if nargin == 3 && isstruct(opts)
    for k = 1:size(fields_opts,1)
        if ~isfield(opts,fields_opts{k,1})
            opts = setfield(opts,fields_opts{k,1},fields_opts{k,2});
        end
    end
else
    opts = cell2struct(fields_opts(:,2),fields_opts(:,1),1);
end

% ======================= PROPIEDADES DE LA TABLA ======================

X = get(hTab,'Data');
colnames = get(hTab,'ColumnName');
[nrows, ncols] = size(X);

% ========================= PLANTILLAS ================================

COL_TEMP = '<TD>_col_</TD>';
ROW_TEMP = '<TR>_row_</TR>';
HEADER_TEMP = '<TH bgcolor=#DCDCFF>_header_</TH>';

HTML_TEMP = ['<html><head><title>_pagetitle_</title></head><body><font face="_fontname_">',...
    '<table border=_borderwidth_ bordercolor=#000000 cellspacing=5 cellpadding=5 bgcolor=_bgcolor_>',...
    ' <caption>_tabletitle_</caption> _table_ </table></font> _footnote_ </body></html>'];

FOOT_TEMP = ['<br><br><br><font face="Arial Narrow" color=#C0C0C0 size=2>',...
    'Published by: <cite>table2html</cite></font>'];

% ========================== ENCABEZADOS  =============================
if strcmp(colnames,'numbered')
    colnames = repmat('untitled|',1,ncols);
    remain = colnames;
    colnames = {};
    while 1
        [str,remain]=strtok(remain,'|');
        if isempty(str),break,end;
        colnames=[colnames str];
    end
end
rstr = WriteHeaders(colnames);
WriteTable(rstr);
web(filename,'-browser');

% =====================================================
    function rstr = WriteHeaders(headers)
        rstr = '';
        for k = 1:ncols
            rstr=[rstr,strrep(HEADER_TEMP,'_header_',headers{k})];
        end
    end

    function WriteTable(rstr)
        [path_,~,~] = fileparts(filename);
        if ~isempty(path_)
            if ~isdir(path_)
                mkdir(path_);
            end
        end
       
        fid=fopen(filename,'w');
        for i=1:nrows
            cstr='';
            for j=1:ncols
                if isa(X,'cell')
                    cstr = [cstr,strrep(COL_TEMP,'_col_',num2str(X{i,j})),' '];
                else
                    cstr = [cstr,strrep(COL_TEMP,'_col_',num2str(X(i,j))),' '];
                end
            end
            rstr = [rstr,strrep(ROW_TEMP,'_row_',cstr)];
        end
        WEB_PAGE = strrep(HTML_TEMP,'_table_',rstr);
        WEB_PAGE = regexprep(WEB_PAGE,{'_footnote_','_bgcolor_',...
            '_fontname_','_borderwidth_','_tabletitle_','_pagetitle_','_fontcolor_'},...
            {FOOT_TEMP,opts.BgColor,opts.FontName,opts.BorderWidth,...
            opts.TableTitle,opts.PageTitle,opts.FontColor});
        fprintf(fid,'%s',WEB_PAGE);
        fclose(fid);
    end

end

Para una referencia más completa con algunos ejemplos/test de la función table2html puede revisar el siguiente enlace:

table2html (GitHub)

martes, 13 de mayo de 2014

Personalizar Push Button en una GUI MATLAB


Cuando se crea un Push Button en una GUI MATLAB existen ciertas limitaciones para personalizar la visualización del mismo. De forma ordinaria se puede modificar el color de fondo mediante la propiedad BackgroundColor, el tamaño de fuente con FontSize, el estilo de fuente con FontWeight, el tipo de fuente con FontName, e incluso poner una imagen de fondo (Véase este post ). No obstante utilizando las bondades del lenguaje HTML se puede disponer de mayores opciones, enseguida se tratarán algunas de las características más importantes que pueden modificarse.

Colocar letras griegas 

En ingeniería es muy común el uso del alfabeto griego para representar diversas magnitudes. Para colocar letras griegas en el "String" del Push Button deben utilizarse las etiquetas HTML y anteponer un ampersand (&) al nombre de la letra griega. Por ejemplo si requiere utilizar la siguiente expresión: $Calcular\,\,\,\beta$, entonces deberá modificar el "String" como se muestra enseguida:

str='<html>Calcular &beta</html>';
set(hPB,'String',str);


En las líneas anteriores hPB es el handle del Push Button (en un Push Button creado con GUIDE se utilizar la referencia handles.tagBoton).


Subíndices y superíndices

En HTML se utilizan las etiquetas <sub></sub> para indicar un subíndice y <sup></sup> para superíndices. Claro, como en el caso anterior estas deben ir entre etiquetas HTML para que MATLAB lo reconozca como tal, véase el siguiente ejemplo en el cual se utiliza como "String" la expresión: $a^2+b^2=k_0$

str='<html>a<sup>2</sup>+b<sup>2</sup>=k<sub>0</sub></html>';
set(hPB,'String',str);



Múltiples líneas

Para colocar más de una linea en un Push Button puede utilizarse la etiqueta HTML de salto de línea <br>, véase el ejemplo a continuación:

str='<html>Primera línea <br> Segunda línea</html>';
set(hPB,'String',str);




Para una referencia más completa acerca de las características HTML vistas en este post puede visitar los siguientes enlaces:


lunes, 12 de mayo de 2014

Visualizador de imágenes


La siguiente GUI hace la función de un visualizador de imágenes, seleccionando una carpeta en la cual estén situadas las imagenes.

function verImg
clearvars('-global')
figure('MenuBar','none',...
    'NumberTitle','off',...
    'Name','Visualizador de imágenes',...
    'Resize','off',...
    'Position',[200 200 450 350]);
centerfig;

uimenu('Label','Seleccionar carpeta','Callback',@selFcn);

ax=axes('units','pixels',...
    'Position',[25 25 400 300],...
    'Visible','off');

uicontrol('style','push',...
    'String','<<',...
    'Position',[0 165 20 20],...
    'Callback',@cambiar);

uicontrol('style','push',...
    'String','>>',...
    'Position',[430 165 20 20],...
    'Callback',@cambiar);

    function selFcn(src,~)
        global carp Imgs cont
        cont=1;
        carp=uigetdir;
        if isequal(carp,0)
            return;
        end
        Imgs=dir([carp,'/*.jpg']);
        imshow(imread([carp,'/',Imgs(cont).name]));
    end

    function cambiar(src,~)
        global carp cont Imgs
        if (strcmp(get(src,'str'),'>>') && cont<length(Imgs))
            cont=cont+1;
            imshow(imread([carp,'/',Imgs(cont).name]));
        elseif (strcmp(get(src,'str'),'<<') && cont>1)
            cont=cont-1;
            imshow(imread([carp,'/',Imgs(cont).name]));
        end
    end
end