Category: Matlab
Category Archives: Matlab
Workaround to Goto problems in Enabled Subsystems
Hello MATLAB Community,
I’m currently working on a Simulink model that includes a Powergui block set to EquivalentMode2 and a Current Measurement block. I need to use an Enabled Subsystem to manage part of my model, but I’m encountering issues with dynamically created Goto blocks when converting the subsystem.
Problem Description:
Setup:
My model includes a Controlled Voltage Source (in AC mode) and a Current Measurement block.
These blocks are part of a larger subsystem that needs to be enabled and disabled based on specific conditions.
Issue:
When I convert the subsystem to an Enabled Subsystem, Simulink dynamically creates Goto blocks within the Powergui’s EquivalentMode2 block, specifically inside the Current Measurement block.
This results in an error: Goto/From connections cannot cross nonvirtual subsystem boundaries.
Steps I’ve Taken:
I tried to manage the Current Measurement using standard Simulink blocks and physical signal converters but encountered issues with solver requirements.In other words, I cant add more complexity to an already fairly complex model, it would take forever.
I also attempted to create custom measurement logic but faced difficulties with integrating it seamlessly into the existing physical simulation. Again, here whatever I do requires a Solver and it turns it unfeasible to run (takes forever).
Error message I got:
Multiple Gotos found with tag named ‘DOC’
Component:Simulink | Category:Model error
First offending Goto ‘integrated_bat_fuel_2/powergui/EquivalentModel2/Yout/Goto2’
Component:Simulink | Category:Model error
Second offending Goto ‘integrated_bat_fuel_2/FuelCell Subsystem/FuelCell 1 kW 24V DC/Fuel Cell Stack/Current Measurement1/source’
Component:Simulink | Category:Model error
Additional Context:
I’m using Simulink with a combination of Simscape Electrical components.
The model involves a mix of physical and Simulink signals, making it critical to maintain compatibility across different simulation domains.
Any guidance or recommendations would be greatly appreciated!
Thank you, [Your Name]
Feel free to modify the draft as needed to better fit your situation or to add any other relevant details.
4o
Any ideas? Please advice , I already ran out of ideas and I have no clue on how to solve this, any guidance or recommendations would be greatly appreciated!
Thank you,
RaulHello MATLAB Community,
I’m currently working on a Simulink model that includes a Powergui block set to EquivalentMode2 and a Current Measurement block. I need to use an Enabled Subsystem to manage part of my model, but I’m encountering issues with dynamically created Goto blocks when converting the subsystem.
Problem Description:
Setup:
My model includes a Controlled Voltage Source (in AC mode) and a Current Measurement block.
These blocks are part of a larger subsystem that needs to be enabled and disabled based on specific conditions.
Issue:
When I convert the subsystem to an Enabled Subsystem, Simulink dynamically creates Goto blocks within the Powergui’s EquivalentMode2 block, specifically inside the Current Measurement block.
This results in an error: Goto/From connections cannot cross nonvirtual subsystem boundaries.
Steps I’ve Taken:
I tried to manage the Current Measurement using standard Simulink blocks and physical signal converters but encountered issues with solver requirements.In other words, I cant add more complexity to an already fairly complex model, it would take forever.
I also attempted to create custom measurement logic but faced difficulties with integrating it seamlessly into the existing physical simulation. Again, here whatever I do requires a Solver and it turns it unfeasible to run (takes forever).
Error message I got:
Multiple Gotos found with tag named ‘DOC’
Component:Simulink | Category:Model error
First offending Goto ‘integrated_bat_fuel_2/powergui/EquivalentModel2/Yout/Goto2’
Component:Simulink | Category:Model error
Second offending Goto ‘integrated_bat_fuel_2/FuelCell Subsystem/FuelCell 1 kW 24V DC/Fuel Cell Stack/Current Measurement1/source’
Component:Simulink | Category:Model error
Additional Context:
I’m using Simulink with a combination of Simscape Electrical components.
The model involves a mix of physical and Simulink signals, making it critical to maintain compatibility across different simulation domains.
Any guidance or recommendations would be greatly appreciated!
Thank you, [Your Name]
Feel free to modify the draft as needed to better fit your situation or to add any other relevant details.
4o
Any ideas? Please advice , I already ran out of ideas and I have no clue on how to solve this, any guidance or recommendations would be greatly appreciated!
Thank you,
Raul Hello MATLAB Community,
I’m currently working on a Simulink model that includes a Powergui block set to EquivalentMode2 and a Current Measurement block. I need to use an Enabled Subsystem to manage part of my model, but I’m encountering issues with dynamically created Goto blocks when converting the subsystem.
Problem Description:
Setup:
My model includes a Controlled Voltage Source (in AC mode) and a Current Measurement block.
These blocks are part of a larger subsystem that needs to be enabled and disabled based on specific conditions.
Issue:
When I convert the subsystem to an Enabled Subsystem, Simulink dynamically creates Goto blocks within the Powergui’s EquivalentMode2 block, specifically inside the Current Measurement block.
This results in an error: Goto/From connections cannot cross nonvirtual subsystem boundaries.
Steps I’ve Taken:
I tried to manage the Current Measurement using standard Simulink blocks and physical signal converters but encountered issues with solver requirements.In other words, I cant add more complexity to an already fairly complex model, it would take forever.
I also attempted to create custom measurement logic but faced difficulties with integrating it seamlessly into the existing physical simulation. Again, here whatever I do requires a Solver and it turns it unfeasible to run (takes forever).
Error message I got:
Multiple Gotos found with tag named ‘DOC’
Component:Simulink | Category:Model error
First offending Goto ‘integrated_bat_fuel_2/powergui/EquivalentModel2/Yout/Goto2’
Component:Simulink | Category:Model error
Second offending Goto ‘integrated_bat_fuel_2/FuelCell Subsystem/FuelCell 1 kW 24V DC/Fuel Cell Stack/Current Measurement1/source’
Component:Simulink | Category:Model error
Additional Context:
I’m using Simulink with a combination of Simscape Electrical components.
The model involves a mix of physical and Simulink signals, making it critical to maintain compatibility across different simulation domains.
Any guidance or recommendations would be greatly appreciated!
Thank you, [Your Name]
Feel free to modify the draft as needed to better fit your situation or to add any other relevant details.
4o
Any ideas? Please advice , I already ran out of ideas and I have no clue on how to solve this, any guidance or recommendations would be greatly appreciated!
Thank you,
Raul simscape, simulink MATLAB Answers — New Questions
Disorganization of other components when adding the HTML component in MATLAB APP DESIGNER
Hello everyone,
I have a small application built in MATLAB APP DESIGNER. It is divided into a 2-PANEL APP (Left and Right). In the Right PANEL, there is a TABGROUP component that contains three TABS: IMAGE; HISTOGRAM; and HELP / SUPPORT, as shown in the figure below:
Inside each TAB, there is a PANEL component, and within each PANEL, I have AXES components for the IMAGE and HISTOGRAM TABS. Everything works fine until I add an HTML component inside the PANEL of the HELP / SUPPORT TAB, which will display a page with information about the application. When I do this, the other components become disorganized, as shown in the figure below.
Below, the figures demonstrate the disorganization of the components in the IMAGE and HISTOGRAM TABS.
Attached is the application code:
classdef segmentacao_palmeiras_tab_exported < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
GridLayout matlab.ui.container.GridLayout
LeftPanel matlab.ui.container.Panel
panelInfo matlab.ui.container.Panel
btnTipoSegmentacao matlab.ui.container.ButtonGroup
optSimples matlab.ui.control.RadioButton
optEspecies matlab.ui.control.RadioButton
txt_InfoGeo matlab.ui.control.Label
lbl_InfoGeo matlab.ui.control.Label
txt_InfoDim matlab.ui.control.Label
lbl_InfoDim matlab.ui.control.Label
txt_InfoLocal matlab.ui.control.Label
lbl_InfoLocal matlab.ui.control.Label
lbl_InfoImagem matlab.ui.control.Label
logoINPA matlab.ui.control.Image
logoUDESC matlab.ui.control.Image
RightPanel matlab.ui.container.Panel
panelBotoes matlab.ui.container.Panel
btnExportar matlab.ui.control.Button
btnHistograma matlab.ui.control.Button
btnProcessar matlab.ui.control.Button
btnCarregarImg matlab.ui.control.Button
TabGroup matlab.ui.container.TabGroup
IMAGEMTab matlab.ui.container.Tab
panelImagem matlab.ui.container.Panel
plotImagem matlab.ui.control.UIAxes
HISTOGRAMATab matlab.ui.container.Tab
panelHistogram matlab.ui.container.Panel
plotHistograma matlab.ui.control.UIAxes
AJUDASUPORTETab matlab.ui.container.Tab
HTML matlab.ui.control.HTML
end
% Properties that correspond to apps with auto-reflow
properties (Access = private)
onePanelWidth = 576;
end
properties (Access = private)
ImageFile % Arquivo de imagem;
ImageFile_pad % Arquivo de imagem ajustado
C_Categorical % Resultado gerado em CATEGORICAL
C_Categorical_Simples % Resultado gerado em CATEGORICAL
C_Uint8 % Resultado gerado em UINT8
C_Uint8_Simples % Resultado gerado em UINT8
B % Overlay da Imagem com o Resultado Espécies
B_Simples % Overlay da Imagem com o Resultado Simples
H % Grafico do Histograma
NetWork % Rede Neural
ImageFile_x % Largura
ImageFile_y % Altura
ImageFile_dim % Nr. Bandas
ImageFile_format % Formato do arquivo
R % Referencia Espacial da Imagem
S % Dados Geográficos geotiffinfo
X % Dados Geográficos struct.geotiffinfo
end
methods (Access = private)
% Tela de Progresso
function d = myprogress(app)
d = uiprogressdlg(app.UIFigure,’Title’,’Por favor aguarde…’,…
‘Message’,’Abrindo a aplicação’);
pause(.5);
d.Value = .33;
d.Message = ‘Carregando os dados necessários’;
pause(1);
d.Value = .67;
d.Message = ‘Processando os dados’;
pause(1);
d.Value = 1;
d.Message = ‘Finalizando’;
pause(1);
% Fecha dialog box
close(d);
end
function resetApp(app)
% Limpar as variáveis
clear;
% Limpar todas as propriedades
app.ImageFile = [];
app.ImageFile_pad = [];
app.C_Categorical = [];
app.C_Categorical_Simples = [];
app.C_Uint8 = [];
app.C_Uint8_Simples = [];
app.B = [];
app.B_Simples = [];
app.H = [];
app.NetWork = [];
app.ImageFile_x = [];
app.ImageFile_y = [];
app.ImageFile_dim = [];
app.ImageFile_format = [];
app.R = [];
app.S = [];
app.X = [];
% Limpar componentes de UI
%cla(app.plotImagem);
%cla(app.plotHistograma);
end
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.UIFigure.Position = [100 100 1100 630]; % [x y width height]
app.UIFigure.Resize = ‘off’;
% Especifica o diretório da exportacao
diretorio = ‘export’;
% Verifica se o diretório existe
if ~isfolder(diretorio)
% Se o diretório não existe, cria o diretório
mkdir(diretorio);
end
% Desabilita/Habilita os botões
app.btnCarregarImg.Enable = true;
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Carregando a rede treinada
try
load(‘./net_cocao.mat’,’net_cocao’);
app.NetWork = net_cocao;
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
end
% Button pushed function: btnCarregarImg
function btnCarregarImgButtonPushed(app, event)
% Limpa a variaveis, propriedades e visualizadores.
app.resetApp();
% Desabilita/Habilita os botões
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optSimples.Value = 0;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Chama a janela para carregar a imagem
% Armazena os dados da imagem do usuario
[filename,filepath] = uigetfile({‘*.tif’}, ‘Selecionar imagem’);
fullname = [filepath, filename];
% Abre a imagem de entrada selecionada pelo usuário
app.ImageFile = imread(fullname);
app.myprogress;
% Armazena informações sobre dimensões da imagem de entrada
[app.ImageFile_x,app.ImageFile_y,app.ImageFile_dim] = size(app.ImageFile);
% Armazena as informações geográficas da Imagem carregada
[~, r] = readgeoraster(fullname);
app.R = r;
app.X = geotiffinfo(fullname);
app.S = struct([app.X.GeoTIFFTags.GeoKeyDirectoryTag]);
app.ImageFile_format = app.X.Format;
% Verifica se o formato da imagem é TIF
if (string(app.ImageFile_format) ~= ‘tif’)
msg = {‘ATENÇÃO!’,’O formato da imagem deve ser TIF.’};
uialert(app.UIFigure,msg,’Warning’,’Icon’,’warning’);
end
% Verifica se o numero de bandas estão
% corretos para utilizar no programa.
if (app.ImageFile_dim ~= 3)
% Para o caso da imagem I tenha mais de 3 bandas deve-se retirar deixando
% somente 3 bandas
% Isolar as bandas da imagem
B1 = app.ImageFile(:,:,1);
B2 = app.ImageFile(:,:,2);
B3 = app.ImageFile(:,:,3);
% Junta as bandas isoladas
app.ImageFile = cat(3, B1, B2, B3);
msg = {‘ATENÇÃO!’,’A imagem de entrada deve ter 3 bandas. A imagem carregada engloba mais de 3 bandas. Foram consideradas somente as 3 primeiras bandas para o processamento.’};
uialert(app.UIFigure,msg,’Aviso’,’Icon’,’warning’);
end
% Ajustar a escala da imgem para a segmentação conforme o
% treinamento feito na CNN 512×512 pixels.
PatchSize = [512, 512];
app.ImageFile = imresize(app.ImageFile,’Scale’, PatchSize ./ 512);
% Apresenta a imagem no applicativo (Plot)
imshow(app.ImageFile,’Parent’,app.plotImagem);
%imagesc(app.plotImagem, app.ImageFile);
% Mostra as informaçções de tamanho e dimensão da imagem
%informacoes = sprintf(‘Arquivo: %ssprintf(‘Arquivo: %sn Tamanho (Bytes): %sn Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);n Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);
%app.txt_InfoLocal.Text = string(informacoes);
app.txt_InfoLocal.Text = string(app.X.Filename);
altura = string("Altura: " + app.X.Height);
largura = string("Largura: " + app.X.Width);
nr_dim = string("Nr. Bandas: " + app.ImageFile_dim);
tamanho = string("Tamanho (Bytes): " + app.X.FileSize);
dimensoes = [altura, largura, nr_dim, tamanho];
app.txt_InfoDim.Text = dimensoes;
app.txt_InfoGeo.Text = string(app.X.PCS);
% Desabilita/Habilita os botões
app.btnProcessar.Enable = true;
app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Button pushed function: btnProcessar
function btnProcessarButtonPushed(app, event)
% Desabilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnExportar.Enable = false;
app.btnHistograma.Enable = false;
% Verifica se a GPU está disponível
useGPU = canUseGPU();
if useGPU
% Limpa a Memoria da GPU antes do processamento
D = gpuDevice();
reset(D);
end
% Cria a função para processar imagens de tamanho grandes por
% blocos
if useGPU
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="gpu",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
else
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="auto",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
end
% Redefine o tamanho do bloco para 512
tamanho_bloco = [512 512];
% Armazena o tamanho da imagem I
[height, width, ~] = size(app.ImageFile);
% Calcula o pad image para obter a dimensão que seja multiplo de tamanho do bloco
padSize(1) = tamanho_bloco(1) – mod(height, tamanho_bloco(1));
padSize(2) = tamanho_bloco(2) – mod(width, tamanho_bloco(2));
% Gera uma cópia da imagem com o tamanho adequado para o tamanho do Bloco.
% o tamanho acrestado (PAD) a imagem é preenchido com valor 0
app.ImageFile_pad = padarray(app.ImageFile, padSize, 0, ‘post’);
% Processa a segmentação
try
% Redefine o tamanho do bloco para 2048
tamanho_bloco = [2048 2048];
C = blockproc(app.ImageFile_pad, tamanho_bloco, fun_proc_semanticseg);
app.myprogress;
% The output is nosy, apply a median filter to remove spurious pixels.
C = medfilt2(C,[5 5]);
% Retorna o resultado para o tamanho original
C = C(1:height, 1:width);
C = changem(C,7,0);
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Definição dos Valores e Nome das Classes (ESPECIES)
labelIDs = [1 2 3 4 5 6 7];
classes = ["Açai" "Cocão" "Jaci" "Paxiuba" "Tucuma" "Floresta" "no-data"];
% Definição dos Valores e Nome das Classes (SIMPLES)
labelIDs_Simples = [1 2 3];
classes_Simples = ["Palmeiras" "Floresta" "no-data"];
% Alterar a segmentacao de ESPECIES -> SIMPLES
C_Simples = C;
C_Simples = changem(C_Simples,3,0);
C_Simples = changem(C_Simples,1,2);
C_Simples = changem(C_Simples,1,3);
C_Simples = changem(C_Simples,1,4);
C_Simples = changem(C_Simples,1,5);
C_Simples = changem(C_Simples,2,6);
C_Simples = changem(C_Simples,3,7);
% Converte a saida da segmentação de UINT8 para Categorical
% possibilitando a exportação.
app.C_Categorical = categorical(C, labelIDs, classes);
app.C_Uint8 = C;
app.C_Categorical_Simples = categorical(C_Simples,labelIDs_Simples,classes_Simples);
app.C_Uint8_Simples = C_Simples;
app.B = labeloverlay(app.ImageFile,C);
app.B_Simples = labeloverlay(app.ImageFile,C_Simples);
% Monta a sobreposição da Imagem com o resultado gerado da
% segmentação
if app.optSimples.Value ~= 1
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B_Simples,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
else % Espécie
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
% Habilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = true;
app.optSimples.Enable = true;
end
% Button pushed function: btnExportar
function btnExportarButtonPushed(app, event)
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnHistograma.Enable = false;
app.btnProcessar.Enable = false;
% Processa a exportação do resultado da segmentação
try
if app.optSimples.Value ~= 1
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8_Simples,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
else
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
end
message = ["Resultado Exportado!","Procure o arquivo classImg.tif na pasta export."];
uialert(app.UIFigure,message,"Sucesso", "Icon","success");
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
end
% Button pushed function: btnHistograma
function btnHistogramaButtonPushed(app, event)
% Processa o histograma do resultado da segmentação
try
% histograma.
if app.optSimples.Value ~= 1
app.H = histogram(app.plotHistograma,app.C_Categorical_Simples …
,"FaceColor",[1 0 0],"EdgeColor","none");
else % Espécie
app.H = histogram(app.plotHistograma,app.C_Categorical …
,"FaceColor",[1 0 0],"EdgeColor","none");
end
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
app.TabGroup.SelectedTab = app.HISTOGRAMATab;
end
% Selection changed function: btnTipoSegmentacao
function btnTipoSegmentacaoSelectionChanged(app, event)
% Escolheu o Tipo Simples
if app.optSimples.Value ~= 1
imshow(app.B_Simples,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical_Simples, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
else % Espécies
imshow(app.B,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
end
end
% Changes arrangement of the app based on UIFigure width
function updateAppLayout(app, event)
currentFigureWidth = app.UIFigure.Position(3);
if(currentFigureWidth <= app.onePanelWidth)
% Change to a 2×1 grid
app.GridLayout.RowHeight = {397, 397};
app.GridLayout.ColumnWidth = {‘1x’};
app.RightPanel.Layout.Row = 2;
app.RightPanel.Layout.Column = 1;
else
% Change to a 1×2 grid
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
end
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Get the file path for locating images
pathToMLAPP = fileparts(mfilename(‘fullpath’));
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.AutoResizeChildren = ‘off’;
app.UIFigure.Position = [100 100 698 397];
app.UIFigure.Name = ‘MATLAB App’;
app.UIFigure.Resize = ‘off’;
app.UIFigure.SizeChangedFcn = createCallbackFcn(app, @updateAppLayout, true);
% Create GridLayout
app.GridLayout = uigridlayout(app.UIFigure);
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnSpacing = 0;
app.GridLayout.RowSpacing = 0;
app.GridLayout.Padding = [0 0 0 0];
app.GridLayout.Scrollable = ‘on’;
% Create LeftPanel
app.LeftPanel = uipanel(app.GridLayout);
app.LeftPanel.Layout.Row = 1;
app.LeftPanel.Layout.Column = 1;
% Create panelInfo
app.panelInfo = uipanel(app.LeftPanel);
app.panelInfo.BorderType = ‘none’;
app.panelInfo.Position = [7 7 200 384];
% Create logoUDESC
app.logoUDESC = uiimage(app.panelInfo);
app.logoUDESC.Position = [8 345 83 34];
app.logoUDESC.ImageSource = fullfile(pathToMLAPP, ‘udesc2_logo.png’);
% Create logoINPA
app.logoINPA = uiimage(app.panelInfo);
app.logoINPA.Position = [110 346 83 34];
app.logoINPA.ImageSource = fullfile(pathToMLAPP, ‘inpa-acre_logo.png’);
% Create lbl_InfoImagem
app.lbl_InfoImagem = uilabel(app.panelInfo);
app.lbl_InfoImagem.HorizontalAlignment = ‘center’;
app.lbl_InfoImagem.FontSize = 14;
app.lbl_InfoImagem.FontWeight = ‘bold’;
app.lbl_InfoImagem.Position = [7 315 186 22];
app.lbl_InfoImagem.Text = ‘Informações da Entrada’;
% Create lbl_InfoLocal
app.lbl_InfoLocal = uilabel(app.panelInfo);
app.lbl_InfoLocal.FontWeight = ‘bold’;
app.lbl_InfoLocal.Position = [7 287 186 22];
app.lbl_InfoLocal.Text = ‘Local:’;
% Create txt_InfoLocal
app.txt_InfoLocal = uilabel(app.panelInfo);
app.txt_InfoLocal.VerticalAlignment = ‘top’;
app.txt_InfoLocal.WordWrap = ‘on’;
app.txt_InfoLocal.FontSize = 9;
app.txt_InfoLocal.Position = [7 246 186 34];
app.txt_InfoLocal.Text = ‘ ‘;
% Create lbl_InfoDim
app.lbl_InfoDim = uilabel(app.panelInfo);
app.lbl_InfoDim.FontWeight = ‘bold’;
app.lbl_InfoDim.Position = [7 218 186 22];
app.lbl_InfoDim.Text = ‘Dimensão:’;
% Create txt_InfoDim
app.txt_InfoDim = uilabel(app.panelInfo);
app.txt_InfoDim.VerticalAlignment = ‘top’;
app.txt_InfoDim.WordWrap = ‘on’;
app.txt_InfoDim.FontSize = 9;
app.txt_InfoDim.Position = [7 131 186 80];
app.txt_InfoDim.Text = ‘ ‘;
% Create lbl_InfoGeo
app.lbl_InfoGeo = uilabel(app.panelInfo);
app.lbl_InfoGeo.FontWeight = ‘bold’;
app.lbl_InfoGeo.Position = [7 106 186 22];
app.lbl_InfoGeo.Text = ‘Dados Geográficos:’;
% Create txt_InfoGeo
app.txt_InfoGeo = uilabel(app.panelInfo);
app.txt_InfoGeo.VerticalAlignment = ‘top’;
app.txt_InfoGeo.WordWrap = ‘on’;
app.txt_InfoGeo.FontSize = 9;
app.txt_InfoGeo.Position = [7 65 186 34];
app.txt_InfoGeo.Text = ‘ ‘;
% Create btnTipoSegmentacao
app.btnTipoSegmentacao = uibuttongroup(app.panelInfo);
app.btnTipoSegmentacao.SelectionChangedFcn = createCallbackFcn(app, @btnTipoSegmentacaoSelectionChanged, true);
app.btnTipoSegmentacao.Title = ‘Tipo de Segmentação:’;
app.btnTipoSegmentacao.Position = [6 10 186 49];
% Create optEspecies
app.optEspecies = uiradiobutton(app.btnTipoSegmentacao);
app.optEspecies.Enable = ‘off’;
app.optEspecies.Text = ‘Simples’;
app.optEspecies.Position = [11 3 64 22];
app.optEspecies.Value = true;
% Create optSimples
app.optSimples = uiradiobutton(app.btnTipoSegmentacao);
app.optSimples.Enable = ‘off’;
app.optSimples.Text = ‘Espécies’;
app.optSimples.Position = [103 3 70 22];
% Create RightPanel
app.RightPanel = uipanel(app.GridLayout);
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
% Create TabGroup
app.TabGroup = uitabgroup(app.RightPanel);
app.TabGroup.AutoResizeChildren = ‘off’;
app.TabGroup.Position = [11 65 467 325];
% Create IMAGEMTab
app.IMAGEMTab = uitab(app.TabGroup);
app.IMAGEMTab.AutoResizeChildren = ‘off’;
app.IMAGEMTab.Title = ‘IMAGEM’;
% Create panelImagem
app.panelImagem = uipanel(app.IMAGEMTab);
app.panelImagem.AutoResizeChildren = ‘off’;
app.panelImagem.BorderType = ‘none’;
app.panelImagem.Position = [8 8 452 284];
% Create plotImagem
app.plotImagem = uiaxes(app.panelImagem);
app.plotImagem.XTick = [];
app.plotImagem.YTick = [];
app.plotImagem.ZTick = [];
app.plotImagem.Color = [0.9412 0.9412 0.9412];
app.plotImagem.Box = ‘on’;
app.plotImagem.Position = [6 8 437 271];
% Create HISTOGRAMATab
app.HISTOGRAMATab = uitab(app.TabGroup);
app.HISTOGRAMATab.AutoResizeChildren = ‘off’;
app.HISTOGRAMATab.Title = ‘HISTOGRAMA’;
% Create panelHistogram
app.panelHistogram = uipanel(app.HISTOGRAMATab);
app.panelHistogram.AutoResizeChildren = ‘off’;
app.panelHistogram.BorderType = ‘none’;
app.panelHistogram.Position = [8 8 452 284];
% Create plotHistograma
app.plotHistograma = uiaxes(app.panelHistogram);
title(app.plotHistograma, ‘Frequência por Espécies’)
xlabel(app.plotHistograma, ‘Espécies de Palmeiras’)
ylabel(app.plotHistograma, ‘Nr. Pixels’)
app.plotHistograma.Toolbar.Visible = ‘off’;
app.plotHistograma.Box = ‘on’;
app.plotHistograma.XGrid = ‘on’;
app.plotHistograma.YGrid = ‘on’;
app.plotHistograma.Position = [6 8 437 271];
% Create AJUDASUPORTETab
app.AJUDASUPORTETab = uitab(app.TabGroup);
app.AJUDASUPORTETab.AutoResizeChildren = ‘off’;
app.AJUDASUPORTETab.Title = ‘AJUDA / SUPORTE’;
% Create HTML
app.HTML = uihtml(app.AJUDASUPORTETab);
app.HTML.HTMLSource = ‘suporte.html’;
app.HTML.Position = [15 14 435 272];
% Create panelBotoes
app.panelBotoes = uipanel(app.RightPanel);
app.panelBotoes.BorderType = ‘none’;
app.panelBotoes.Position = [12 7 465 48];
% Create btnCarregarImg
app.btnCarregarImg = uibutton(app.panelBotoes, ‘push’);
app.btnCarregarImg.ButtonPushedFcn = createCallbackFcn(app, @btnCarregarImgButtonPushed, true);
app.btnCarregarImg.WordWrap = ‘on’;
app.btnCarregarImg.Position = [21 8 91 35];
app.btnCarregarImg.Text = ‘Carregar Imagem…’;
% Create btnProcessar
app.btnProcessar = uibutton(app.panelBotoes, ‘push’);
app.btnProcessar.ButtonPushedFcn = createCallbackFcn(app, @btnProcessarButtonPushed, true);
app.btnProcessar.WordWrap = ‘on’;
app.btnProcessar.Enable = ‘off’;
app.btnProcessar.Position = [132 8 91 35];
app.btnProcessar.Text = ‘Processar Segmentação’;
% Create btnHistograma
app.btnHistograma = uibutton(app.panelBotoes, ‘push’);
app.btnHistograma.ButtonPushedFcn = createCallbackFcn(app, @btnHistogramaButtonPushed, true);
app.btnHistograma.WordWrap = ‘on’;
app.btnHistograma.Enable = ‘off’;
app.btnHistograma.Position = [243 8 91 35];
app.btnHistograma.Text = ‘Histograma’;
% Create btnExportar
app.btnExportar = uibutton(app.panelBotoes, ‘push’);
app.btnExportar.ButtonPushedFcn = createCallbackFcn(app, @btnExportarButtonPushed, true);
app.btnExportar.WordWrap = ‘on’;
app.btnExportar.Enable = ‘off’;
app.btnExportar.Position = [354 8 91 35];
app.btnExportar.Text = ‘Exportar Segmentação’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = segmentacao_palmeiras_tab_exported
runningApp = getRunningApp(app);
% Check for running singleton app
if isempty(runningApp)
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
else
% Focus the running singleton app
figure(runningApp.UIFigure)
app = runningApp;
end
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
Could someone please help me resolve this issue?
Best regards,
Airton Gaio Jr.Hello everyone,
I have a small application built in MATLAB APP DESIGNER. It is divided into a 2-PANEL APP (Left and Right). In the Right PANEL, there is a TABGROUP component that contains three TABS: IMAGE; HISTOGRAM; and HELP / SUPPORT, as shown in the figure below:
Inside each TAB, there is a PANEL component, and within each PANEL, I have AXES components for the IMAGE and HISTOGRAM TABS. Everything works fine until I add an HTML component inside the PANEL of the HELP / SUPPORT TAB, which will display a page with information about the application. When I do this, the other components become disorganized, as shown in the figure below.
Below, the figures demonstrate the disorganization of the components in the IMAGE and HISTOGRAM TABS.
Attached is the application code:
classdef segmentacao_palmeiras_tab_exported < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
GridLayout matlab.ui.container.GridLayout
LeftPanel matlab.ui.container.Panel
panelInfo matlab.ui.container.Panel
btnTipoSegmentacao matlab.ui.container.ButtonGroup
optSimples matlab.ui.control.RadioButton
optEspecies matlab.ui.control.RadioButton
txt_InfoGeo matlab.ui.control.Label
lbl_InfoGeo matlab.ui.control.Label
txt_InfoDim matlab.ui.control.Label
lbl_InfoDim matlab.ui.control.Label
txt_InfoLocal matlab.ui.control.Label
lbl_InfoLocal matlab.ui.control.Label
lbl_InfoImagem matlab.ui.control.Label
logoINPA matlab.ui.control.Image
logoUDESC matlab.ui.control.Image
RightPanel matlab.ui.container.Panel
panelBotoes matlab.ui.container.Panel
btnExportar matlab.ui.control.Button
btnHistograma matlab.ui.control.Button
btnProcessar matlab.ui.control.Button
btnCarregarImg matlab.ui.control.Button
TabGroup matlab.ui.container.TabGroup
IMAGEMTab matlab.ui.container.Tab
panelImagem matlab.ui.container.Panel
plotImagem matlab.ui.control.UIAxes
HISTOGRAMATab matlab.ui.container.Tab
panelHistogram matlab.ui.container.Panel
plotHistograma matlab.ui.control.UIAxes
AJUDASUPORTETab matlab.ui.container.Tab
HTML matlab.ui.control.HTML
end
% Properties that correspond to apps with auto-reflow
properties (Access = private)
onePanelWidth = 576;
end
properties (Access = private)
ImageFile % Arquivo de imagem;
ImageFile_pad % Arquivo de imagem ajustado
C_Categorical % Resultado gerado em CATEGORICAL
C_Categorical_Simples % Resultado gerado em CATEGORICAL
C_Uint8 % Resultado gerado em UINT8
C_Uint8_Simples % Resultado gerado em UINT8
B % Overlay da Imagem com o Resultado Espécies
B_Simples % Overlay da Imagem com o Resultado Simples
H % Grafico do Histograma
NetWork % Rede Neural
ImageFile_x % Largura
ImageFile_y % Altura
ImageFile_dim % Nr. Bandas
ImageFile_format % Formato do arquivo
R % Referencia Espacial da Imagem
S % Dados Geográficos geotiffinfo
X % Dados Geográficos struct.geotiffinfo
end
methods (Access = private)
% Tela de Progresso
function d = myprogress(app)
d = uiprogressdlg(app.UIFigure,’Title’,’Por favor aguarde…’,…
‘Message’,’Abrindo a aplicação’);
pause(.5);
d.Value = .33;
d.Message = ‘Carregando os dados necessários’;
pause(1);
d.Value = .67;
d.Message = ‘Processando os dados’;
pause(1);
d.Value = 1;
d.Message = ‘Finalizando’;
pause(1);
% Fecha dialog box
close(d);
end
function resetApp(app)
% Limpar as variáveis
clear;
% Limpar todas as propriedades
app.ImageFile = [];
app.ImageFile_pad = [];
app.C_Categorical = [];
app.C_Categorical_Simples = [];
app.C_Uint8 = [];
app.C_Uint8_Simples = [];
app.B = [];
app.B_Simples = [];
app.H = [];
app.NetWork = [];
app.ImageFile_x = [];
app.ImageFile_y = [];
app.ImageFile_dim = [];
app.ImageFile_format = [];
app.R = [];
app.S = [];
app.X = [];
% Limpar componentes de UI
%cla(app.plotImagem);
%cla(app.plotHistograma);
end
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.UIFigure.Position = [100 100 1100 630]; % [x y width height]
app.UIFigure.Resize = ‘off’;
% Especifica o diretório da exportacao
diretorio = ‘export’;
% Verifica se o diretório existe
if ~isfolder(diretorio)
% Se o diretório não existe, cria o diretório
mkdir(diretorio);
end
% Desabilita/Habilita os botões
app.btnCarregarImg.Enable = true;
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Carregando a rede treinada
try
load(‘./net_cocao.mat’,’net_cocao’);
app.NetWork = net_cocao;
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
end
% Button pushed function: btnCarregarImg
function btnCarregarImgButtonPushed(app, event)
% Limpa a variaveis, propriedades e visualizadores.
app.resetApp();
% Desabilita/Habilita os botões
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optSimples.Value = 0;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Chama a janela para carregar a imagem
% Armazena os dados da imagem do usuario
[filename,filepath] = uigetfile({‘*.tif’}, ‘Selecionar imagem’);
fullname = [filepath, filename];
% Abre a imagem de entrada selecionada pelo usuário
app.ImageFile = imread(fullname);
app.myprogress;
% Armazena informações sobre dimensões da imagem de entrada
[app.ImageFile_x,app.ImageFile_y,app.ImageFile_dim] = size(app.ImageFile);
% Armazena as informações geográficas da Imagem carregada
[~, r] = readgeoraster(fullname);
app.R = r;
app.X = geotiffinfo(fullname);
app.S = struct([app.X.GeoTIFFTags.GeoKeyDirectoryTag]);
app.ImageFile_format = app.X.Format;
% Verifica se o formato da imagem é TIF
if (string(app.ImageFile_format) ~= ‘tif’)
msg = {‘ATENÇÃO!’,’O formato da imagem deve ser TIF.’};
uialert(app.UIFigure,msg,’Warning’,’Icon’,’warning’);
end
% Verifica se o numero de bandas estão
% corretos para utilizar no programa.
if (app.ImageFile_dim ~= 3)
% Para o caso da imagem I tenha mais de 3 bandas deve-se retirar deixando
% somente 3 bandas
% Isolar as bandas da imagem
B1 = app.ImageFile(:,:,1);
B2 = app.ImageFile(:,:,2);
B3 = app.ImageFile(:,:,3);
% Junta as bandas isoladas
app.ImageFile = cat(3, B1, B2, B3);
msg = {‘ATENÇÃO!’,’A imagem de entrada deve ter 3 bandas. A imagem carregada engloba mais de 3 bandas. Foram consideradas somente as 3 primeiras bandas para o processamento.’};
uialert(app.UIFigure,msg,’Aviso’,’Icon’,’warning’);
end
% Ajustar a escala da imgem para a segmentação conforme o
% treinamento feito na CNN 512×512 pixels.
PatchSize = [512, 512];
app.ImageFile = imresize(app.ImageFile,’Scale’, PatchSize ./ 512);
% Apresenta a imagem no applicativo (Plot)
imshow(app.ImageFile,’Parent’,app.plotImagem);
%imagesc(app.plotImagem, app.ImageFile);
% Mostra as informaçções de tamanho e dimensão da imagem
%informacoes = sprintf(‘Arquivo: %ssprintf(‘Arquivo: %sn Tamanho (Bytes): %sn Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);n Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);
%app.txt_InfoLocal.Text = string(informacoes);
app.txt_InfoLocal.Text = string(app.X.Filename);
altura = string("Altura: " + app.X.Height);
largura = string("Largura: " + app.X.Width);
nr_dim = string("Nr. Bandas: " + app.ImageFile_dim);
tamanho = string("Tamanho (Bytes): " + app.X.FileSize);
dimensoes = [altura, largura, nr_dim, tamanho];
app.txt_InfoDim.Text = dimensoes;
app.txt_InfoGeo.Text = string(app.X.PCS);
% Desabilita/Habilita os botões
app.btnProcessar.Enable = true;
app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Button pushed function: btnProcessar
function btnProcessarButtonPushed(app, event)
% Desabilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnExportar.Enable = false;
app.btnHistograma.Enable = false;
% Verifica se a GPU está disponível
useGPU = canUseGPU();
if useGPU
% Limpa a Memoria da GPU antes do processamento
D = gpuDevice();
reset(D);
end
% Cria a função para processar imagens de tamanho grandes por
% blocos
if useGPU
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="gpu",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
else
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="auto",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
end
% Redefine o tamanho do bloco para 512
tamanho_bloco = [512 512];
% Armazena o tamanho da imagem I
[height, width, ~] = size(app.ImageFile);
% Calcula o pad image para obter a dimensão que seja multiplo de tamanho do bloco
padSize(1) = tamanho_bloco(1) – mod(height, tamanho_bloco(1));
padSize(2) = tamanho_bloco(2) – mod(width, tamanho_bloco(2));
% Gera uma cópia da imagem com o tamanho adequado para o tamanho do Bloco.
% o tamanho acrestado (PAD) a imagem é preenchido com valor 0
app.ImageFile_pad = padarray(app.ImageFile, padSize, 0, ‘post’);
% Processa a segmentação
try
% Redefine o tamanho do bloco para 2048
tamanho_bloco = [2048 2048];
C = blockproc(app.ImageFile_pad, tamanho_bloco, fun_proc_semanticseg);
app.myprogress;
% The output is nosy, apply a median filter to remove spurious pixels.
C = medfilt2(C,[5 5]);
% Retorna o resultado para o tamanho original
C = C(1:height, 1:width);
C = changem(C,7,0);
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Definição dos Valores e Nome das Classes (ESPECIES)
labelIDs = [1 2 3 4 5 6 7];
classes = ["Açai" "Cocão" "Jaci" "Paxiuba" "Tucuma" "Floresta" "no-data"];
% Definição dos Valores e Nome das Classes (SIMPLES)
labelIDs_Simples = [1 2 3];
classes_Simples = ["Palmeiras" "Floresta" "no-data"];
% Alterar a segmentacao de ESPECIES -> SIMPLES
C_Simples = C;
C_Simples = changem(C_Simples,3,0);
C_Simples = changem(C_Simples,1,2);
C_Simples = changem(C_Simples,1,3);
C_Simples = changem(C_Simples,1,4);
C_Simples = changem(C_Simples,1,5);
C_Simples = changem(C_Simples,2,6);
C_Simples = changem(C_Simples,3,7);
% Converte a saida da segmentação de UINT8 para Categorical
% possibilitando a exportação.
app.C_Categorical = categorical(C, labelIDs, classes);
app.C_Uint8 = C;
app.C_Categorical_Simples = categorical(C_Simples,labelIDs_Simples,classes_Simples);
app.C_Uint8_Simples = C_Simples;
app.B = labeloverlay(app.ImageFile,C);
app.B_Simples = labeloverlay(app.ImageFile,C_Simples);
% Monta a sobreposição da Imagem com o resultado gerado da
% segmentação
if app.optSimples.Value ~= 1
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B_Simples,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
else % Espécie
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
% Habilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = true;
app.optSimples.Enable = true;
end
% Button pushed function: btnExportar
function btnExportarButtonPushed(app, event)
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnHistograma.Enable = false;
app.btnProcessar.Enable = false;
% Processa a exportação do resultado da segmentação
try
if app.optSimples.Value ~= 1
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8_Simples,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
else
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
end
message = ["Resultado Exportado!","Procure o arquivo classImg.tif na pasta export."];
uialert(app.UIFigure,message,"Sucesso", "Icon","success");
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
end
% Button pushed function: btnHistograma
function btnHistogramaButtonPushed(app, event)
% Processa o histograma do resultado da segmentação
try
% histograma.
if app.optSimples.Value ~= 1
app.H = histogram(app.plotHistograma,app.C_Categorical_Simples …
,"FaceColor",[1 0 0],"EdgeColor","none");
else % Espécie
app.H = histogram(app.plotHistograma,app.C_Categorical …
,"FaceColor",[1 0 0],"EdgeColor","none");
end
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
app.TabGroup.SelectedTab = app.HISTOGRAMATab;
end
% Selection changed function: btnTipoSegmentacao
function btnTipoSegmentacaoSelectionChanged(app, event)
% Escolheu o Tipo Simples
if app.optSimples.Value ~= 1
imshow(app.B_Simples,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical_Simples, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
else % Espécies
imshow(app.B,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
end
end
% Changes arrangement of the app based on UIFigure width
function updateAppLayout(app, event)
currentFigureWidth = app.UIFigure.Position(3);
if(currentFigureWidth <= app.onePanelWidth)
% Change to a 2×1 grid
app.GridLayout.RowHeight = {397, 397};
app.GridLayout.ColumnWidth = {‘1x’};
app.RightPanel.Layout.Row = 2;
app.RightPanel.Layout.Column = 1;
else
% Change to a 1×2 grid
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
end
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Get the file path for locating images
pathToMLAPP = fileparts(mfilename(‘fullpath’));
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.AutoResizeChildren = ‘off’;
app.UIFigure.Position = [100 100 698 397];
app.UIFigure.Name = ‘MATLAB App’;
app.UIFigure.Resize = ‘off’;
app.UIFigure.SizeChangedFcn = createCallbackFcn(app, @updateAppLayout, true);
% Create GridLayout
app.GridLayout = uigridlayout(app.UIFigure);
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnSpacing = 0;
app.GridLayout.RowSpacing = 0;
app.GridLayout.Padding = [0 0 0 0];
app.GridLayout.Scrollable = ‘on’;
% Create LeftPanel
app.LeftPanel = uipanel(app.GridLayout);
app.LeftPanel.Layout.Row = 1;
app.LeftPanel.Layout.Column = 1;
% Create panelInfo
app.panelInfo = uipanel(app.LeftPanel);
app.panelInfo.BorderType = ‘none’;
app.panelInfo.Position = [7 7 200 384];
% Create logoUDESC
app.logoUDESC = uiimage(app.panelInfo);
app.logoUDESC.Position = [8 345 83 34];
app.logoUDESC.ImageSource = fullfile(pathToMLAPP, ‘udesc2_logo.png’);
% Create logoINPA
app.logoINPA = uiimage(app.panelInfo);
app.logoINPA.Position = [110 346 83 34];
app.logoINPA.ImageSource = fullfile(pathToMLAPP, ‘inpa-acre_logo.png’);
% Create lbl_InfoImagem
app.lbl_InfoImagem = uilabel(app.panelInfo);
app.lbl_InfoImagem.HorizontalAlignment = ‘center’;
app.lbl_InfoImagem.FontSize = 14;
app.lbl_InfoImagem.FontWeight = ‘bold’;
app.lbl_InfoImagem.Position = [7 315 186 22];
app.lbl_InfoImagem.Text = ‘Informações da Entrada’;
% Create lbl_InfoLocal
app.lbl_InfoLocal = uilabel(app.panelInfo);
app.lbl_InfoLocal.FontWeight = ‘bold’;
app.lbl_InfoLocal.Position = [7 287 186 22];
app.lbl_InfoLocal.Text = ‘Local:’;
% Create txt_InfoLocal
app.txt_InfoLocal = uilabel(app.panelInfo);
app.txt_InfoLocal.VerticalAlignment = ‘top’;
app.txt_InfoLocal.WordWrap = ‘on’;
app.txt_InfoLocal.FontSize = 9;
app.txt_InfoLocal.Position = [7 246 186 34];
app.txt_InfoLocal.Text = ‘ ‘;
% Create lbl_InfoDim
app.lbl_InfoDim = uilabel(app.panelInfo);
app.lbl_InfoDim.FontWeight = ‘bold’;
app.lbl_InfoDim.Position = [7 218 186 22];
app.lbl_InfoDim.Text = ‘Dimensão:’;
% Create txt_InfoDim
app.txt_InfoDim = uilabel(app.panelInfo);
app.txt_InfoDim.VerticalAlignment = ‘top’;
app.txt_InfoDim.WordWrap = ‘on’;
app.txt_InfoDim.FontSize = 9;
app.txt_InfoDim.Position = [7 131 186 80];
app.txt_InfoDim.Text = ‘ ‘;
% Create lbl_InfoGeo
app.lbl_InfoGeo = uilabel(app.panelInfo);
app.lbl_InfoGeo.FontWeight = ‘bold’;
app.lbl_InfoGeo.Position = [7 106 186 22];
app.lbl_InfoGeo.Text = ‘Dados Geográficos:’;
% Create txt_InfoGeo
app.txt_InfoGeo = uilabel(app.panelInfo);
app.txt_InfoGeo.VerticalAlignment = ‘top’;
app.txt_InfoGeo.WordWrap = ‘on’;
app.txt_InfoGeo.FontSize = 9;
app.txt_InfoGeo.Position = [7 65 186 34];
app.txt_InfoGeo.Text = ‘ ‘;
% Create btnTipoSegmentacao
app.btnTipoSegmentacao = uibuttongroup(app.panelInfo);
app.btnTipoSegmentacao.SelectionChangedFcn = createCallbackFcn(app, @btnTipoSegmentacaoSelectionChanged, true);
app.btnTipoSegmentacao.Title = ‘Tipo de Segmentação:’;
app.btnTipoSegmentacao.Position = [6 10 186 49];
% Create optEspecies
app.optEspecies = uiradiobutton(app.btnTipoSegmentacao);
app.optEspecies.Enable = ‘off’;
app.optEspecies.Text = ‘Simples’;
app.optEspecies.Position = [11 3 64 22];
app.optEspecies.Value = true;
% Create optSimples
app.optSimples = uiradiobutton(app.btnTipoSegmentacao);
app.optSimples.Enable = ‘off’;
app.optSimples.Text = ‘Espécies’;
app.optSimples.Position = [103 3 70 22];
% Create RightPanel
app.RightPanel = uipanel(app.GridLayout);
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
% Create TabGroup
app.TabGroup = uitabgroup(app.RightPanel);
app.TabGroup.AutoResizeChildren = ‘off’;
app.TabGroup.Position = [11 65 467 325];
% Create IMAGEMTab
app.IMAGEMTab = uitab(app.TabGroup);
app.IMAGEMTab.AutoResizeChildren = ‘off’;
app.IMAGEMTab.Title = ‘IMAGEM’;
% Create panelImagem
app.panelImagem = uipanel(app.IMAGEMTab);
app.panelImagem.AutoResizeChildren = ‘off’;
app.panelImagem.BorderType = ‘none’;
app.panelImagem.Position = [8 8 452 284];
% Create plotImagem
app.plotImagem = uiaxes(app.panelImagem);
app.plotImagem.XTick = [];
app.plotImagem.YTick = [];
app.plotImagem.ZTick = [];
app.plotImagem.Color = [0.9412 0.9412 0.9412];
app.plotImagem.Box = ‘on’;
app.plotImagem.Position = [6 8 437 271];
% Create HISTOGRAMATab
app.HISTOGRAMATab = uitab(app.TabGroup);
app.HISTOGRAMATab.AutoResizeChildren = ‘off’;
app.HISTOGRAMATab.Title = ‘HISTOGRAMA’;
% Create panelHistogram
app.panelHistogram = uipanel(app.HISTOGRAMATab);
app.panelHistogram.AutoResizeChildren = ‘off’;
app.panelHistogram.BorderType = ‘none’;
app.panelHistogram.Position = [8 8 452 284];
% Create plotHistograma
app.plotHistograma = uiaxes(app.panelHistogram);
title(app.plotHistograma, ‘Frequência por Espécies’)
xlabel(app.plotHistograma, ‘Espécies de Palmeiras’)
ylabel(app.plotHistograma, ‘Nr. Pixels’)
app.plotHistograma.Toolbar.Visible = ‘off’;
app.plotHistograma.Box = ‘on’;
app.plotHistograma.XGrid = ‘on’;
app.plotHistograma.YGrid = ‘on’;
app.plotHistograma.Position = [6 8 437 271];
% Create AJUDASUPORTETab
app.AJUDASUPORTETab = uitab(app.TabGroup);
app.AJUDASUPORTETab.AutoResizeChildren = ‘off’;
app.AJUDASUPORTETab.Title = ‘AJUDA / SUPORTE’;
% Create HTML
app.HTML = uihtml(app.AJUDASUPORTETab);
app.HTML.HTMLSource = ‘suporte.html’;
app.HTML.Position = [15 14 435 272];
% Create panelBotoes
app.panelBotoes = uipanel(app.RightPanel);
app.panelBotoes.BorderType = ‘none’;
app.panelBotoes.Position = [12 7 465 48];
% Create btnCarregarImg
app.btnCarregarImg = uibutton(app.panelBotoes, ‘push’);
app.btnCarregarImg.ButtonPushedFcn = createCallbackFcn(app, @btnCarregarImgButtonPushed, true);
app.btnCarregarImg.WordWrap = ‘on’;
app.btnCarregarImg.Position = [21 8 91 35];
app.btnCarregarImg.Text = ‘Carregar Imagem…’;
% Create btnProcessar
app.btnProcessar = uibutton(app.panelBotoes, ‘push’);
app.btnProcessar.ButtonPushedFcn = createCallbackFcn(app, @btnProcessarButtonPushed, true);
app.btnProcessar.WordWrap = ‘on’;
app.btnProcessar.Enable = ‘off’;
app.btnProcessar.Position = [132 8 91 35];
app.btnProcessar.Text = ‘Processar Segmentação’;
% Create btnHistograma
app.btnHistograma = uibutton(app.panelBotoes, ‘push’);
app.btnHistograma.ButtonPushedFcn = createCallbackFcn(app, @btnHistogramaButtonPushed, true);
app.btnHistograma.WordWrap = ‘on’;
app.btnHistograma.Enable = ‘off’;
app.btnHistograma.Position = [243 8 91 35];
app.btnHistograma.Text = ‘Histograma’;
% Create btnExportar
app.btnExportar = uibutton(app.panelBotoes, ‘push’);
app.btnExportar.ButtonPushedFcn = createCallbackFcn(app, @btnExportarButtonPushed, true);
app.btnExportar.WordWrap = ‘on’;
app.btnExportar.Enable = ‘off’;
app.btnExportar.Position = [354 8 91 35];
app.btnExportar.Text = ‘Exportar Segmentação’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = segmentacao_palmeiras_tab_exported
runningApp = getRunningApp(app);
% Check for running singleton app
if isempty(runningApp)
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
else
% Focus the running singleton app
figure(runningApp.UIFigure)
app = runningApp;
end
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
Could someone please help me resolve this issue?
Best regards,
Airton Gaio Jr. Hello everyone,
I have a small application built in MATLAB APP DESIGNER. It is divided into a 2-PANEL APP (Left and Right). In the Right PANEL, there is a TABGROUP component that contains three TABS: IMAGE; HISTOGRAM; and HELP / SUPPORT, as shown in the figure below:
Inside each TAB, there is a PANEL component, and within each PANEL, I have AXES components for the IMAGE and HISTOGRAM TABS. Everything works fine until I add an HTML component inside the PANEL of the HELP / SUPPORT TAB, which will display a page with information about the application. When I do this, the other components become disorganized, as shown in the figure below.
Below, the figures demonstrate the disorganization of the components in the IMAGE and HISTOGRAM TABS.
Attached is the application code:
classdef segmentacao_palmeiras_tab_exported < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
GridLayout matlab.ui.container.GridLayout
LeftPanel matlab.ui.container.Panel
panelInfo matlab.ui.container.Panel
btnTipoSegmentacao matlab.ui.container.ButtonGroup
optSimples matlab.ui.control.RadioButton
optEspecies matlab.ui.control.RadioButton
txt_InfoGeo matlab.ui.control.Label
lbl_InfoGeo matlab.ui.control.Label
txt_InfoDim matlab.ui.control.Label
lbl_InfoDim matlab.ui.control.Label
txt_InfoLocal matlab.ui.control.Label
lbl_InfoLocal matlab.ui.control.Label
lbl_InfoImagem matlab.ui.control.Label
logoINPA matlab.ui.control.Image
logoUDESC matlab.ui.control.Image
RightPanel matlab.ui.container.Panel
panelBotoes matlab.ui.container.Panel
btnExportar matlab.ui.control.Button
btnHistograma matlab.ui.control.Button
btnProcessar matlab.ui.control.Button
btnCarregarImg matlab.ui.control.Button
TabGroup matlab.ui.container.TabGroup
IMAGEMTab matlab.ui.container.Tab
panelImagem matlab.ui.container.Panel
plotImagem matlab.ui.control.UIAxes
HISTOGRAMATab matlab.ui.container.Tab
panelHistogram matlab.ui.container.Panel
plotHistograma matlab.ui.control.UIAxes
AJUDASUPORTETab matlab.ui.container.Tab
HTML matlab.ui.control.HTML
end
% Properties that correspond to apps with auto-reflow
properties (Access = private)
onePanelWidth = 576;
end
properties (Access = private)
ImageFile % Arquivo de imagem;
ImageFile_pad % Arquivo de imagem ajustado
C_Categorical % Resultado gerado em CATEGORICAL
C_Categorical_Simples % Resultado gerado em CATEGORICAL
C_Uint8 % Resultado gerado em UINT8
C_Uint8_Simples % Resultado gerado em UINT8
B % Overlay da Imagem com o Resultado Espécies
B_Simples % Overlay da Imagem com o Resultado Simples
H % Grafico do Histograma
NetWork % Rede Neural
ImageFile_x % Largura
ImageFile_y % Altura
ImageFile_dim % Nr. Bandas
ImageFile_format % Formato do arquivo
R % Referencia Espacial da Imagem
S % Dados Geográficos geotiffinfo
X % Dados Geográficos struct.geotiffinfo
end
methods (Access = private)
% Tela de Progresso
function d = myprogress(app)
d = uiprogressdlg(app.UIFigure,’Title’,’Por favor aguarde…’,…
‘Message’,’Abrindo a aplicação’);
pause(.5);
d.Value = .33;
d.Message = ‘Carregando os dados necessários’;
pause(1);
d.Value = .67;
d.Message = ‘Processando os dados’;
pause(1);
d.Value = 1;
d.Message = ‘Finalizando’;
pause(1);
% Fecha dialog box
close(d);
end
function resetApp(app)
% Limpar as variáveis
clear;
% Limpar todas as propriedades
app.ImageFile = [];
app.ImageFile_pad = [];
app.C_Categorical = [];
app.C_Categorical_Simples = [];
app.C_Uint8 = [];
app.C_Uint8_Simples = [];
app.B = [];
app.B_Simples = [];
app.H = [];
app.NetWork = [];
app.ImageFile_x = [];
app.ImageFile_y = [];
app.ImageFile_dim = [];
app.ImageFile_format = [];
app.R = [];
app.S = [];
app.X = [];
% Limpar componentes de UI
%cla(app.plotImagem);
%cla(app.plotHistograma);
end
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.UIFigure.Position = [100 100 1100 630]; % [x y width height]
app.UIFigure.Resize = ‘off’;
% Especifica o diretório da exportacao
diretorio = ‘export’;
% Verifica se o diretório existe
if ~isfolder(diretorio)
% Se o diretório não existe, cria o diretório
mkdir(diretorio);
end
% Desabilita/Habilita os botões
app.btnCarregarImg.Enable = true;
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Carregando a rede treinada
try
load(‘./net_cocao.mat’,’net_cocao’);
app.NetWork = net_cocao;
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
end
% Button pushed function: btnCarregarImg
function btnCarregarImgButtonPushed(app, event)
% Limpa a variaveis, propriedades e visualizadores.
app.resetApp();
% Desabilita/Habilita os botões
app.btnProcessar.Enable = false;
app.btnHistograma.Enable = false;
app.btnExportar.Enable = false;
% Desabilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optSimples.Value = 0;
app.optEspecies.Enable = false;
app.optSimples.Enable = false;
% Chama a janela para carregar a imagem
% Armazena os dados da imagem do usuario
[filename,filepath] = uigetfile({‘*.tif’}, ‘Selecionar imagem’);
fullname = [filepath, filename];
% Abre a imagem de entrada selecionada pelo usuário
app.ImageFile = imread(fullname);
app.myprogress;
% Armazena informações sobre dimensões da imagem de entrada
[app.ImageFile_x,app.ImageFile_y,app.ImageFile_dim] = size(app.ImageFile);
% Armazena as informações geográficas da Imagem carregada
[~, r] = readgeoraster(fullname);
app.R = r;
app.X = geotiffinfo(fullname);
app.S = struct([app.X.GeoTIFFTags.GeoKeyDirectoryTag]);
app.ImageFile_format = app.X.Format;
% Verifica se o formato da imagem é TIF
if (string(app.ImageFile_format) ~= ‘tif’)
msg = {‘ATENÇÃO!’,’O formato da imagem deve ser TIF.’};
uialert(app.UIFigure,msg,’Warning’,’Icon’,’warning’);
end
% Verifica se o numero de bandas estão
% corretos para utilizar no programa.
if (app.ImageFile_dim ~= 3)
% Para o caso da imagem I tenha mais de 3 bandas deve-se retirar deixando
% somente 3 bandas
% Isolar as bandas da imagem
B1 = app.ImageFile(:,:,1);
B2 = app.ImageFile(:,:,2);
B3 = app.ImageFile(:,:,3);
% Junta as bandas isoladas
app.ImageFile = cat(3, B1, B2, B3);
msg = {‘ATENÇÃO!’,’A imagem de entrada deve ter 3 bandas. A imagem carregada engloba mais de 3 bandas. Foram consideradas somente as 3 primeiras bandas para o processamento.’};
uialert(app.UIFigure,msg,’Aviso’,’Icon’,’warning’);
end
% Ajustar a escala da imgem para a segmentação conforme o
% treinamento feito na CNN 512×512 pixels.
PatchSize = [512, 512];
app.ImageFile = imresize(app.ImageFile,’Scale’, PatchSize ./ 512);
% Apresenta a imagem no applicativo (Plot)
imshow(app.ImageFile,’Parent’,app.plotImagem);
%imagesc(app.plotImagem, app.ImageFile);
% Mostra as informaçções de tamanho e dimensão da imagem
%informacoes = sprintf(‘Arquivo: %ssprintf(‘Arquivo: %sn Tamanho (Bytes): %sn Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);n Altura: %sn Largula: %sn Nr. Bandas: %sn DATUM/Projeção: %sn’,app.X.Filename, app.X.FileSize, app.X.Height, app.X.Width, app.ImageFile_dim, app.X.PCS);
%app.txt_InfoLocal.Text = string(informacoes);
app.txt_InfoLocal.Text = string(app.X.Filename);
altura = string("Altura: " + app.X.Height);
largura = string("Largura: " + app.X.Width);
nr_dim = string("Nr. Bandas: " + app.ImageFile_dim);
tamanho = string("Tamanho (Bytes): " + app.X.FileSize);
dimensoes = [altura, largura, nr_dim, tamanho];
app.txt_InfoDim.Text = dimensoes;
app.txt_InfoGeo.Text = string(app.X.PCS);
% Desabilita/Habilita os botões
app.btnProcessar.Enable = true;
app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Button pushed function: btnProcessar
function btnProcessarButtonPushed(app, event)
% Desabilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnExportar.Enable = false;
app.btnHistograma.Enable = false;
% Verifica se a GPU está disponível
useGPU = canUseGPU();
if useGPU
% Limpa a Memoria da GPU antes do processamento
D = gpuDevice();
reset(D);
end
% Cria a função para processar imagens de tamanho grandes por
% blocos
if useGPU
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="gpu",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
else
fun_proc_semanticseg = @(bloco)semanticseg(bloco.data, app.NetWork,ExecutionEnvironment="auto",MiniBatchSize=16,OutputType="uint8",Acceleration="auto");
end
% Redefine o tamanho do bloco para 512
tamanho_bloco = [512 512];
% Armazena o tamanho da imagem I
[height, width, ~] = size(app.ImageFile);
% Calcula o pad image para obter a dimensão que seja multiplo de tamanho do bloco
padSize(1) = tamanho_bloco(1) – mod(height, tamanho_bloco(1));
padSize(2) = tamanho_bloco(2) – mod(width, tamanho_bloco(2));
% Gera uma cópia da imagem com o tamanho adequado para o tamanho do Bloco.
% o tamanho acrestado (PAD) a imagem é preenchido com valor 0
app.ImageFile_pad = padarray(app.ImageFile, padSize, 0, ‘post’);
% Processa a segmentação
try
% Redefine o tamanho do bloco para 2048
tamanho_bloco = [2048 2048];
C = blockproc(app.ImageFile_pad, tamanho_bloco, fun_proc_semanticseg);
app.myprogress;
% The output is nosy, apply a median filter to remove spurious pixels.
C = medfilt2(C,[5 5]);
% Retorna o resultado para o tamanho original
C = C(1:height, 1:width);
C = changem(C,7,0);
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Definição dos Valores e Nome das Classes (ESPECIES)
labelIDs = [1 2 3 4 5 6 7];
classes = ["Açai" "Cocão" "Jaci" "Paxiuba" "Tucuma" "Floresta" "no-data"];
% Definição dos Valores e Nome das Classes (SIMPLES)
labelIDs_Simples = [1 2 3];
classes_Simples = ["Palmeiras" "Floresta" "no-data"];
% Alterar a segmentacao de ESPECIES -> SIMPLES
C_Simples = C;
C_Simples = changem(C_Simples,3,0);
C_Simples = changem(C_Simples,1,2);
C_Simples = changem(C_Simples,1,3);
C_Simples = changem(C_Simples,1,4);
C_Simples = changem(C_Simples,1,5);
C_Simples = changem(C_Simples,2,6);
C_Simples = changem(C_Simples,3,7);
% Converte a saida da segmentação de UINT8 para Categorical
% possibilitando a exportação.
app.C_Categorical = categorical(C, labelIDs, classes);
app.C_Uint8 = C;
app.C_Categorical_Simples = categorical(C_Simples,labelIDs_Simples,classes_Simples);
app.C_Uint8_Simples = C_Simples;
app.B = labeloverlay(app.ImageFile,C);
app.B_Simples = labeloverlay(app.ImageFile,C_Simples);
% Monta a sobreposição da Imagem com o resultado gerado da
% segmentação
if app.optSimples.Value ~= 1
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B_Simples,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
else % Espécie
% Apresenta o resultado da segmentação no applicativo (Plot)
%imagesc(app.plotImagem, B);
imshow(app.B,’Parent’,app.plotImagem);
%app.TabGroup.SelectedTab = app.IMAGEMTab;
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
% Habilita os tipos de segmentação
app.btnTipoSegmentacao.Enable = true;
app.optEspecies.Enable = true;
app.optSimples.Enable = true;
end
% Button pushed function: btnExportar
function btnExportarButtonPushed(app, event)
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = false;
app.btnHistograma.Enable = false;
app.btnProcessar.Enable = false;
% Processa a exportação do resultado da segmentação
try
if app.optSimples.Value ~= 1
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8_Simples,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
else
geotiffwrite(‘./export/classImg.tif’,app.C_Uint8,app.R,’GeoKeyDirectoryTag’,app.S);
app.myprogress;
end
message = ["Resultado Exportado!","Procure o arquivo classImg.tif na pasta export."];
uialert(app.UIFigure,message,"Sucesso", "Icon","success");
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
% Habilita o botão de Exportar/Carregar até o termino do processamento
app.btnCarregarImg.Enable = true;
app.btnHistograma.Enable = true;
app.btnExportar.Enable = true;
app.btnProcessar.Enable = false;
end
% Button pushed function: btnHistograma
function btnHistogramaButtonPushed(app, event)
% Processa o histograma do resultado da segmentação
try
% histograma.
if app.optSimples.Value ~= 1
app.H = histogram(app.plotHistograma,app.C_Categorical_Simples …
,"FaceColor",[1 0 0],"EdgeColor","none");
else % Espécie
app.H = histogram(app.plotHistograma,app.C_Categorical …
,"FaceColor",[1 0 0],"EdgeColor","none");
end
catch ME
report = getReport(ME);
uialert(app.UIFigure,report,’Erro’,’Interpreter’,’html’);
end
app.TabGroup.SelectedTab = app.HISTOGRAMATab;
end
% Selection changed function: btnTipoSegmentacao
function btnTipoSegmentacaoSelectionChanged(app, event)
% Escolheu o Tipo Simples
if app.optSimples.Value ~= 1
imshow(app.B_Simples,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical_Simples, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
else % Espécies
imshow(app.B,’Parent’,app.plotImagem);
app.TabGroup.SelectedTab = app.IMAGEMTab;
% Verifica se existe o histograma
if isprop(app, ‘H’) && ~isempty(app.H)
app.H = histogram(app.plotHistograma, app.C_Categorical, …
‘FaceColor’, [1 0 0], ‘EdgeColor’, ‘none’);
end
end
end
% Changes arrangement of the app based on UIFigure width
function updateAppLayout(app, event)
currentFigureWidth = app.UIFigure.Position(3);
if(currentFigureWidth <= app.onePanelWidth)
% Change to a 2×1 grid
app.GridLayout.RowHeight = {397, 397};
app.GridLayout.ColumnWidth = {‘1x’};
app.RightPanel.Layout.Row = 2;
app.RightPanel.Layout.Column = 1;
else
% Change to a 1×2 grid
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
end
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Get the file path for locating images
pathToMLAPP = fileparts(mfilename(‘fullpath’));
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.AutoResizeChildren = ‘off’;
app.UIFigure.Position = [100 100 698 397];
app.UIFigure.Name = ‘MATLAB App’;
app.UIFigure.Resize = ‘off’;
app.UIFigure.SizeChangedFcn = createCallbackFcn(app, @updateAppLayout, true);
% Create GridLayout
app.GridLayout = uigridlayout(app.UIFigure);
app.GridLayout.ColumnWidth = {212, ‘1x’};
app.GridLayout.RowHeight = {‘1x’};
app.GridLayout.ColumnSpacing = 0;
app.GridLayout.RowSpacing = 0;
app.GridLayout.Padding = [0 0 0 0];
app.GridLayout.Scrollable = ‘on’;
% Create LeftPanel
app.LeftPanel = uipanel(app.GridLayout);
app.LeftPanel.Layout.Row = 1;
app.LeftPanel.Layout.Column = 1;
% Create panelInfo
app.panelInfo = uipanel(app.LeftPanel);
app.panelInfo.BorderType = ‘none’;
app.panelInfo.Position = [7 7 200 384];
% Create logoUDESC
app.logoUDESC = uiimage(app.panelInfo);
app.logoUDESC.Position = [8 345 83 34];
app.logoUDESC.ImageSource = fullfile(pathToMLAPP, ‘udesc2_logo.png’);
% Create logoINPA
app.logoINPA = uiimage(app.panelInfo);
app.logoINPA.Position = [110 346 83 34];
app.logoINPA.ImageSource = fullfile(pathToMLAPP, ‘inpa-acre_logo.png’);
% Create lbl_InfoImagem
app.lbl_InfoImagem = uilabel(app.panelInfo);
app.lbl_InfoImagem.HorizontalAlignment = ‘center’;
app.lbl_InfoImagem.FontSize = 14;
app.lbl_InfoImagem.FontWeight = ‘bold’;
app.lbl_InfoImagem.Position = [7 315 186 22];
app.lbl_InfoImagem.Text = ‘Informações da Entrada’;
% Create lbl_InfoLocal
app.lbl_InfoLocal = uilabel(app.panelInfo);
app.lbl_InfoLocal.FontWeight = ‘bold’;
app.lbl_InfoLocal.Position = [7 287 186 22];
app.lbl_InfoLocal.Text = ‘Local:’;
% Create txt_InfoLocal
app.txt_InfoLocal = uilabel(app.panelInfo);
app.txt_InfoLocal.VerticalAlignment = ‘top’;
app.txt_InfoLocal.WordWrap = ‘on’;
app.txt_InfoLocal.FontSize = 9;
app.txt_InfoLocal.Position = [7 246 186 34];
app.txt_InfoLocal.Text = ‘ ‘;
% Create lbl_InfoDim
app.lbl_InfoDim = uilabel(app.panelInfo);
app.lbl_InfoDim.FontWeight = ‘bold’;
app.lbl_InfoDim.Position = [7 218 186 22];
app.lbl_InfoDim.Text = ‘Dimensão:’;
% Create txt_InfoDim
app.txt_InfoDim = uilabel(app.panelInfo);
app.txt_InfoDim.VerticalAlignment = ‘top’;
app.txt_InfoDim.WordWrap = ‘on’;
app.txt_InfoDim.FontSize = 9;
app.txt_InfoDim.Position = [7 131 186 80];
app.txt_InfoDim.Text = ‘ ‘;
% Create lbl_InfoGeo
app.lbl_InfoGeo = uilabel(app.panelInfo);
app.lbl_InfoGeo.FontWeight = ‘bold’;
app.lbl_InfoGeo.Position = [7 106 186 22];
app.lbl_InfoGeo.Text = ‘Dados Geográficos:’;
% Create txt_InfoGeo
app.txt_InfoGeo = uilabel(app.panelInfo);
app.txt_InfoGeo.VerticalAlignment = ‘top’;
app.txt_InfoGeo.WordWrap = ‘on’;
app.txt_InfoGeo.FontSize = 9;
app.txt_InfoGeo.Position = [7 65 186 34];
app.txt_InfoGeo.Text = ‘ ‘;
% Create btnTipoSegmentacao
app.btnTipoSegmentacao = uibuttongroup(app.panelInfo);
app.btnTipoSegmentacao.SelectionChangedFcn = createCallbackFcn(app, @btnTipoSegmentacaoSelectionChanged, true);
app.btnTipoSegmentacao.Title = ‘Tipo de Segmentação:’;
app.btnTipoSegmentacao.Position = [6 10 186 49];
% Create optEspecies
app.optEspecies = uiradiobutton(app.btnTipoSegmentacao);
app.optEspecies.Enable = ‘off’;
app.optEspecies.Text = ‘Simples’;
app.optEspecies.Position = [11 3 64 22];
app.optEspecies.Value = true;
% Create optSimples
app.optSimples = uiradiobutton(app.btnTipoSegmentacao);
app.optSimples.Enable = ‘off’;
app.optSimples.Text = ‘Espécies’;
app.optSimples.Position = [103 3 70 22];
% Create RightPanel
app.RightPanel = uipanel(app.GridLayout);
app.RightPanel.Layout.Row = 1;
app.RightPanel.Layout.Column = 2;
% Create TabGroup
app.TabGroup = uitabgroup(app.RightPanel);
app.TabGroup.AutoResizeChildren = ‘off’;
app.TabGroup.Position = [11 65 467 325];
% Create IMAGEMTab
app.IMAGEMTab = uitab(app.TabGroup);
app.IMAGEMTab.AutoResizeChildren = ‘off’;
app.IMAGEMTab.Title = ‘IMAGEM’;
% Create panelImagem
app.panelImagem = uipanel(app.IMAGEMTab);
app.panelImagem.AutoResizeChildren = ‘off’;
app.panelImagem.BorderType = ‘none’;
app.panelImagem.Position = [8 8 452 284];
% Create plotImagem
app.plotImagem = uiaxes(app.panelImagem);
app.plotImagem.XTick = [];
app.plotImagem.YTick = [];
app.plotImagem.ZTick = [];
app.plotImagem.Color = [0.9412 0.9412 0.9412];
app.plotImagem.Box = ‘on’;
app.plotImagem.Position = [6 8 437 271];
% Create HISTOGRAMATab
app.HISTOGRAMATab = uitab(app.TabGroup);
app.HISTOGRAMATab.AutoResizeChildren = ‘off’;
app.HISTOGRAMATab.Title = ‘HISTOGRAMA’;
% Create panelHistogram
app.panelHistogram = uipanel(app.HISTOGRAMATab);
app.panelHistogram.AutoResizeChildren = ‘off’;
app.panelHistogram.BorderType = ‘none’;
app.panelHistogram.Position = [8 8 452 284];
% Create plotHistograma
app.plotHistograma = uiaxes(app.panelHistogram);
title(app.plotHistograma, ‘Frequência por Espécies’)
xlabel(app.plotHistograma, ‘Espécies de Palmeiras’)
ylabel(app.plotHistograma, ‘Nr. Pixels’)
app.plotHistograma.Toolbar.Visible = ‘off’;
app.plotHistograma.Box = ‘on’;
app.plotHistograma.XGrid = ‘on’;
app.plotHistograma.YGrid = ‘on’;
app.plotHistograma.Position = [6 8 437 271];
% Create AJUDASUPORTETab
app.AJUDASUPORTETab = uitab(app.TabGroup);
app.AJUDASUPORTETab.AutoResizeChildren = ‘off’;
app.AJUDASUPORTETab.Title = ‘AJUDA / SUPORTE’;
% Create HTML
app.HTML = uihtml(app.AJUDASUPORTETab);
app.HTML.HTMLSource = ‘suporte.html’;
app.HTML.Position = [15 14 435 272];
% Create panelBotoes
app.panelBotoes = uipanel(app.RightPanel);
app.panelBotoes.BorderType = ‘none’;
app.panelBotoes.Position = [12 7 465 48];
% Create btnCarregarImg
app.btnCarregarImg = uibutton(app.panelBotoes, ‘push’);
app.btnCarregarImg.ButtonPushedFcn = createCallbackFcn(app, @btnCarregarImgButtonPushed, true);
app.btnCarregarImg.WordWrap = ‘on’;
app.btnCarregarImg.Position = [21 8 91 35];
app.btnCarregarImg.Text = ‘Carregar Imagem…’;
% Create btnProcessar
app.btnProcessar = uibutton(app.panelBotoes, ‘push’);
app.btnProcessar.ButtonPushedFcn = createCallbackFcn(app, @btnProcessarButtonPushed, true);
app.btnProcessar.WordWrap = ‘on’;
app.btnProcessar.Enable = ‘off’;
app.btnProcessar.Position = [132 8 91 35];
app.btnProcessar.Text = ‘Processar Segmentação’;
% Create btnHistograma
app.btnHistograma = uibutton(app.panelBotoes, ‘push’);
app.btnHistograma.ButtonPushedFcn = createCallbackFcn(app, @btnHistogramaButtonPushed, true);
app.btnHistograma.WordWrap = ‘on’;
app.btnHistograma.Enable = ‘off’;
app.btnHistograma.Position = [243 8 91 35];
app.btnHistograma.Text = ‘Histograma’;
% Create btnExportar
app.btnExportar = uibutton(app.panelBotoes, ‘push’);
app.btnExportar.ButtonPushedFcn = createCallbackFcn(app, @btnExportarButtonPushed, true);
app.btnExportar.WordWrap = ‘on’;
app.btnExportar.Enable = ‘off’;
app.btnExportar.Position = [354 8 91 35];
app.btnExportar.Text = ‘Exportar Segmentação’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = segmentacao_palmeiras_tab_exported
runningApp = getRunningApp(app);
% Check for running singleton app
if isempty(runningApp)
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
else
% Focus the running singleton app
figure(runningApp.UIFigure)
app = runningApp;
end
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
Could someone please help me resolve this issue?
Best regards,
Airton Gaio Jr. app designer, disorganization, components html, components axes MATLAB Answers — New Questions
Programmatically get all block parameters
Some blocks have special parameters, that are not listed in
get_parameter(block, ‘DialogParameters’)
get_parameter(block, ‘ObjectParamters’)
For example, the MATLAB function block reveals its content with the object in
get_param(block, ‘MATLABFunctionConfiguration’)
Which is listed in neither. How to get a list of all a block’s parameters, even exotic ones? Is there maybe a block object to circumvent such an awkward search, for specific parameters you don’t even know exist?Some blocks have special parameters, that are not listed in
get_parameter(block, ‘DialogParameters’)
get_parameter(block, ‘ObjectParamters’)
For example, the MATLAB function block reveals its content with the object in
get_param(block, ‘MATLABFunctionConfiguration’)
Which is listed in neither. How to get a list of all a block’s parameters, even exotic ones? Is there maybe a block object to circumvent such an awkward search, for specific parameters you don’t even know exist? Some blocks have special parameters, that are not listed in
get_parameter(block, ‘DialogParameters’)
get_parameter(block, ‘ObjectParamters’)
For example, the MATLAB function block reveals its content with the object in
get_param(block, ‘MATLABFunctionConfiguration’)
Which is listed in neither. How to get a list of all a block’s parameters, even exotic ones? Is there maybe a block object to circumvent such an awkward search, for specific parameters you don’t even know exist? get_param, hidden, block, parameters MATLAB Answers — New Questions
Simulink – STM32 – PIL test communication error
I have a Simulink model that contain an algorithm block. I built the generated c code succesfully to STM32F4-discovery board. (I read that from diagnostic viewer.) I used SIL/PIL Manager App to make PIL test. I selected serial communication at configuration panel. When I run the PIL simulation I get this error:
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should:
(a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct.
(b) Confirm that the target application is running on the target hardware.
(c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.).
Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
This is my example model:
This is the diagnostic viewer outputs:
### Connectivity configuration for "C:UsersatakanDesktopmilpilsilmult_ert_rtw": STM32F4-Discovery (Serial) ###
### Preparing to start PIL block simulation: denemepil/mult …
### Using toolchain: GNU Tools for ARM Embedded Processors
### ‘C:UsersatakanDesktopmilpilsilmult_ert_rtwpilmult.mk’ is up to date
### Building ‘mult’: "D:MATLABbinwin64gmake" -f mult.mk all MW_GNU_ARM_TOOLS_PATH = C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>cd . C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>if "" == "" ("D:MATLABbinwin64gmake" -f mult.mk all ) else ("D:MATLABbinwin64gmake" -f mult.mk )
"### Invoking postbuild tool "Binary Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O binary ./mult.elf ../../mult.bin
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Hex Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O ihex ./mult.elf ../../mult.hex
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Executable Size" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-size" ./mult.elf text data bss dec hex filename 16748 160 12016 28924 70fc ./mult.elf
"### Done invoking postbuild tool."
"### Successfully generated all binary outputs." C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>exit 0
### Starting application: ‘mult_ert_rtwpilmult.elf’
### Started new OpenOCD process with PID 19356.
### Terminated OpenOCD process with PID 19356.
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should: (a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct. (b) Confirm that the target application is running on the target hardware. (c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.). Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
How can I fix this?I have a Simulink model that contain an algorithm block. I built the generated c code succesfully to STM32F4-discovery board. (I read that from diagnostic viewer.) I used SIL/PIL Manager App to make PIL test. I selected serial communication at configuration panel. When I run the PIL simulation I get this error:
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should:
(a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct.
(b) Confirm that the target application is running on the target hardware.
(c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.).
Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
This is my example model:
This is the diagnostic viewer outputs:
### Connectivity configuration for "C:UsersatakanDesktopmilpilsilmult_ert_rtw": STM32F4-Discovery (Serial) ###
### Preparing to start PIL block simulation: denemepil/mult …
### Using toolchain: GNU Tools for ARM Embedded Processors
### ‘C:UsersatakanDesktopmilpilsilmult_ert_rtwpilmult.mk’ is up to date
### Building ‘mult’: "D:MATLABbinwin64gmake" -f mult.mk all MW_GNU_ARM_TOOLS_PATH = C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>cd . C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>if "" == "" ("D:MATLABbinwin64gmake" -f mult.mk all ) else ("D:MATLABbinwin64gmake" -f mult.mk )
"### Invoking postbuild tool "Binary Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O binary ./mult.elf ../../mult.bin
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Hex Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O ihex ./mult.elf ../../mult.hex
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Executable Size" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-size" ./mult.elf text data bss dec hex filename 16748 160 12016 28924 70fc ./mult.elf
"### Done invoking postbuild tool."
"### Successfully generated all binary outputs." C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>exit 0
### Starting application: ‘mult_ert_rtwpilmult.elf’
### Started new OpenOCD process with PID 19356.
### Terminated OpenOCD process with PID 19356.
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should: (a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct. (b) Confirm that the target application is running on the target hardware. (c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.). Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
How can I fix this? I have a Simulink model that contain an algorithm block. I built the generated c code succesfully to STM32F4-discovery board. (I read that from diagnostic viewer.) I used SIL/PIL Manager App to make PIL test. I selected serial communication at configuration panel. When I run the PIL simulation I get this error:
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should:
(a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct.
(b) Confirm that the target application is running on the target hardware.
(c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.).
Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
This is my example model:
This is the diagnostic viewer outputs:
### Connectivity configuration for "C:UsersatakanDesktopmilpilsilmult_ert_rtw": STM32F4-Discovery (Serial) ###
### Preparing to start PIL block simulation: denemepil/mult …
### Using toolchain: GNU Tools for ARM Embedded Processors
### ‘C:UsersatakanDesktopmilpilsilmult_ert_rtwpilmult.mk’ is up to date
### Building ‘mult’: "D:MATLABbinwin64gmake" -f mult.mk all MW_GNU_ARM_TOOLS_PATH = C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>cd . C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>if "" == "" ("D:MATLABbinwin64gmake" -f mult.mk all ) else ("D:MATLABbinwin64gmake" -f mult.mk )
"### Invoking postbuild tool "Binary Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O binary ./mult.elf ../../mult.bin
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Hex Converter" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-objcopy" -O ihex ./mult.elf ../../mult.hex
"### Done invoking postbuild tool."
"### Invoking postbuild tool "Executable Size" …" "C:/PROGRA~3/MATLAB/SUPPOR~1/R2020b/3P778C~1.INS/GNUARM~1.INS/win/bin/arm-none-eabi-size" ./mult.elf text data bss dec hex filename 16748 160 12016 28924 70fc ./mult.elf
"### Done invoking postbuild tool."
"### Successfully generated all binary outputs." C:UsersatakanDesktopmilpilsilmult_ert_rtwpil>exit 0
### Starting application: ‘mult_ert_rtwpilmult.elf’
### Started new OpenOCD process with PID 19356.
### Terminated OpenOCD process with PID 19356.
The timeout of 10 seconds for receiving data from the rtiostream interface has been exceeded. There might be multiple reasons for this communications failure. You should: (a) Check that the target hardware configuration is correct, for example, check that the byte ordering is correct. (b) Confirm that the target application is running on the target hardware. (c) Consider the possibility of application run-time failures (e.g. divide by zero exceptions, incorrect custom code integration, etc.). Note (c): To identify possible reasons for the run-time failure, consider using SIL, which supports signal handlers and debugging. If you cannot find a solution, consider using the method setTimeoutRecvSecs of rtw.connectivity.RtIOStreamHostCommunicator to increase the timeout value.
How can I fix this? embedded coder, pil, stm32f4, stm32, serial, processor in the loop, sil/pil manager MATLAB Answers — New Questions
Squizzed help display in File Exchange contribution tab
Hi all,
I am a contributor to the file exchange, and recently I noticed the help I provide with my file (‘doc.m’ compiled via the command publish(‘doc.m’); ) is now completely squizzed / shrinked in a scrolling menu which is less than an inch height.
You can see it in my MP toolbox here for instance, but also here and probably in all my files which have an help and maybe also in all the files of the Matlab file exchange.
Do you know how to fix / solve this and come back to the previous display ?
Thank you for your help.
Cheers,
NicolasHi all,
I am a contributor to the file exchange, and recently I noticed the help I provide with my file (‘doc.m’ compiled via the command publish(‘doc.m’); ) is now completely squizzed / shrinked in a scrolling menu which is less than an inch height.
You can see it in my MP toolbox here for instance, but also here and probably in all my files which have an help and maybe also in all the files of the Matlab file exchange.
Do you know how to fix / solve this and come back to the previous display ?
Thank you for your help.
Cheers,
Nicolas Hi all,
I am a contributor to the file exchange, and recently I noticed the help I provide with my file (‘doc.m’ compiled via the command publish(‘doc.m’); ) is now completely squizzed / shrinked in a scrolling menu which is less than an inch height.
You can see it in my MP toolbox here for instance, but also here and probably in all my files which have an help and maybe also in all the files of the Matlab file exchange.
Do you know how to fix / solve this and come back to the previous display ?
Thank you for your help.
Cheers,
Nicolas help, tab, fex, file, exchange, squizzed, shrinked, display MATLAB Answers — New Questions
What hardware Matlab Online uses?
I am trying to find what kind of resources Matlab Online uses, since I need to provide the environment for my project, but I can’t find it anywhere. Does anyone know what kind of hardware resources Matlab Online uses?I am trying to find what kind of resources Matlab Online uses, since I need to provide the environment for my project, but I can’t find it anywhere. Does anyone know what kind of hardware resources Matlab Online uses? I am trying to find what kind of resources Matlab Online uses, since I need to provide the environment for my project, but I can’t find it anywhere. Does anyone know what kind of hardware resources Matlab Online uses? hardware, matlab online MATLAB Answers — New Questions
Can’t load datasets in EEGLAB using script
I’m trying to create a loop that can load and preprocess EEG data sets, here is my code and the reoccuring error
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
%% Get the list of subjects to load:
dataset = uigetdir;%allows user to manually select the folder where the data sets are stored
subjectlist = dir(dataset);
subjectlist = subjectlist(~ismember({subjectlist.name},{‘.’,’..’}));
SUB = {subjectlist(:).name};
filepath = {subjectlist(:).folder};
%%
%load data
for i = 1 : length(SUB)
% 0. Select subject id:
%subject = subjectlist(i);
% Print info to the command window
% display(‘Processing Subject %sn’, SUB(i));
%Define subject path based on study directory and subject ID of current subject
Subject_Path = filepath{i};
Subject_Path = convertCharsToStrings(Subject_Path);
% 1. Load subject data:
% subject_data = load_subject_data(cfg,subject);
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset(‘filename’, SUB{i},’filepath’, Subject_Path);
EEG = eeg_checkset(EEG);
end
eeglab redraw;I’m trying to create a loop that can load and preprocess EEG data sets, here is my code and the reoccuring error
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
%% Get the list of subjects to load:
dataset = uigetdir;%allows user to manually select the folder where the data sets are stored
subjectlist = dir(dataset);
subjectlist = subjectlist(~ismember({subjectlist.name},{‘.’,’..’}));
SUB = {subjectlist(:).name};
filepath = {subjectlist(:).folder};
%%
%load data
for i = 1 : length(SUB)
% 0. Select subject id:
%subject = subjectlist(i);
% Print info to the command window
% display(‘Processing Subject %sn’, SUB(i));
%Define subject path based on study directory and subject ID of current subject
Subject_Path = filepath{i};
Subject_Path = convertCharsToStrings(Subject_Path);
% 1. Load subject data:
% subject_data = load_subject_data(cfg,subject);
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset(‘filename’, SUB{i},’filepath’, Subject_Path);
EEG = eeg_checkset(EEG);
end
eeglab redraw; I’m trying to create a loop that can load and preprocess EEG data sets, here is my code and the reoccuring error
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
%% Get the list of subjects to load:
dataset = uigetdir;%allows user to manually select the folder where the data sets are stored
subjectlist = dir(dataset);
subjectlist = subjectlist(~ismember({subjectlist.name},{‘.’,’..’}));
SUB = {subjectlist(:).name};
filepath = {subjectlist(:).folder};
%%
%load data
for i = 1 : length(SUB)
% 0. Select subject id:
%subject = subjectlist(i);
% Print info to the command window
% display(‘Processing Subject %sn’, SUB(i));
%Define subject path based on study directory and subject ID of current subject
Subject_Path = filepath{i};
Subject_Path = convertCharsToStrings(Subject_Path);
% 1. Load subject data:
% subject_data = load_subject_data(cfg,subject);
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset(‘filename’, SUB{i},’filepath’, Subject_Path);
EEG = eeg_checkset(EEG);
end
eeglab redraw; eeglab, error MATLAB Answers — New Questions
ANFIS output extraction to excel file
I have a fis that was saved to workspace. I want to obtain a matrix or excel file that have all the outputs belong to the created fis. I have to normalize the dataset so i need all fis output as a matrix. It is a little bit emergency. I hope smb can help me about this issue.I have a fis that was saved to workspace. I want to obtain a matrix or excel file that have all the outputs belong to the created fis. I have to normalize the dataset so i need all fis output as a matrix. It is a little bit emergency. I hope smb can help me about this issue. I have a fis that was saved to workspace. I want to obtain a matrix or excel file that have all the outputs belong to the created fis. I have to normalize the dataset so i need all fis output as a matrix. It is a little bit emergency. I hope smb can help me about this issue. anfis, output, fis output, excel extraction MATLAB Answers — New Questions
What is the difference between sim (RL toolbox) and directly click “run” in the Simulink Model
sim – Simulate trained reinforcement learning agents within specified environment
After training my RL agent I use TestSim = sim(agent,env) to test my trained agent.
However, I find that the agent performence is different and much worse if I directly click run bottom is the Simulink model pannel rather than using sim command.
I have checked that in my Simulink model the RL agent block has correctly quoted my trained agent in the MATLAB workspacesim – Simulate trained reinforcement learning agents within specified environment
After training my RL agent I use TestSim = sim(agent,env) to test my trained agent.
However, I find that the agent performence is different and much worse if I directly click run bottom is the Simulink model pannel rather than using sim command.
I have checked that in my Simulink model the RL agent block has correctly quoted my trained agent in the MATLAB workspace sim – Simulate trained reinforcement learning agents within specified environment
After training my RL agent I use TestSim = sim(agent,env) to test my trained agent.
However, I find that the agent performence is different and much worse if I directly click run bottom is the Simulink model pannel rather than using sim command.
I have checked that in my Simulink model the RL agent block has correctly quoted my trained agent in the MATLAB workspace simulink, reinforcement learning, agent MATLAB Answers — New Questions
What does the weight of the fir filter mean?
What does the weight of the fir filter mean?
Is it multiplied by a certain physical quantity of the sound wave?
Like the Taylor series, does it get closer to the true value as the degree increases?
https://kr.mathworks.com/matlabcentral/fileexchange/159311-kalman-filter-for-active-noise-controlWhat does the weight of the fir filter mean?
Is it multiplied by a certain physical quantity of the sound wave?
Like the Taylor series, does it get closer to the true value as the degree increases?
https://kr.mathworks.com/matlabcentral/fileexchange/159311-kalman-filter-for-active-noise-control What does the weight of the fir filter mean?
Is it multiplied by a certain physical quantity of the sound wave?
Like the Taylor series, does it get closer to the true value as the degree increases?
https://kr.mathworks.com/matlabcentral/fileexchange/159311-kalman-filter-for-active-noise-control filter MATLAB Answers — New Questions
How to call functions from another m file
I have two scripts. In first script I have some functions.
script1.m:
function res = func1(a)
res = a * 5;
end
function res = func2(x)
res = x .^ 2;
end
In second script I call these functions. How to include script1.m in second script and call functions from script1.m?I have two scripts. In first script I have some functions.
script1.m:
function res = func1(a)
res = a * 5;
end
function res = func2(x)
res = x .^ 2;
end
In second script I call these functions. How to include script1.m in second script and call functions from script1.m? I have two scripts. In first script I have some functions.
script1.m:
function res = func1(a)
res = a * 5;
end
function res = func2(x)
res = x .^ 2;
end
In second script I call these functions. How to include script1.m in second script and call functions from script1.m? functions, load MATLAB Answers — New Questions
How to make contourf image semitransparent?
I am using contourf to plot a 2D image in jet like below. Now I plan to make it semitransparent, therefore I may add some more lines. I tried all solutions searched online. Seems not working. Would anyone help me out?I am using contourf to plot a 2D image in jet like below. Now I plan to make it semitransparent, therefore I may add some more lines. I tried all solutions searched online. Seems not working. Would anyone help me out? I am using contourf to plot a 2D image in jet like below. Now I plan to make it semitransparent, therefore I may add some more lines. I tried all solutions searched online. Seems not working. Would anyone help me out? contourf MATLAB Answers — New Questions
How to custom the Storage Class in Code Mapping?
I want to use my custom Storage Class when I use Code Mapping in R2024a, how to do that? I tried it in R2018b, and it can be set in code generation selection by clicking right mouse button. Unfortunately, this option has been removed in versions after R2018b.I want to use my custom Storage Class when I use Code Mapping in R2024a, how to do that? I tried it in R2018b, and it can be set in code generation selection by clicking right mouse button. Unfortunately, this option has been removed in versions after R2018b. I want to use my custom Storage Class when I use Code Mapping in R2024a, how to do that? I tried it in R2018b, and it can be set in code generation selection by clicking right mouse button. Unfortunately, this option has been removed in versions after R2018b. code generation, simulink MATLAB Answers — New Questions
rotate polygon in geographic axes
I have a n-sided polygon with vertices as (lat,lon) coordinates. I plot this on a geographic axes. I want to rotate it and end up with a new rotated set of (lat,lon) coordinates. I don’t want a filled polygon, but perhaps I could adjust the transparency if that’s the only way (such as patch). Here is what I tried, but not sure it works accurately due to the oblate earth surface. I prefer not to use Mapping Toolbox, but just core Matlab.
geoplot(lat,lon,’k-‘)
polyin = polyshape([lat’,lon’]);
refPoint = [refLat, refLon];
polyout = rotate(polyin, angleDeg, refPoint);
lat = [polyout.Vertices(:,1); polyout.Vertices(1,1)];
lon = [polyout.Vertices(:,2); polyout.Vertices(1,2)];
geoplot(lat,lon,’b–‘)I have a n-sided polygon with vertices as (lat,lon) coordinates. I plot this on a geographic axes. I want to rotate it and end up with a new rotated set of (lat,lon) coordinates. I don’t want a filled polygon, but perhaps I could adjust the transparency if that’s the only way (such as patch). Here is what I tried, but not sure it works accurately due to the oblate earth surface. I prefer not to use Mapping Toolbox, but just core Matlab.
geoplot(lat,lon,’k-‘)
polyin = polyshape([lat’,lon’]);
refPoint = [refLat, refLon];
polyout = rotate(polyin, angleDeg, refPoint);
lat = [polyout.Vertices(:,1); polyout.Vertices(1,1)];
lon = [polyout.Vertices(:,2); polyout.Vertices(1,2)];
geoplot(lat,lon,’b–‘) I have a n-sided polygon with vertices as (lat,lon) coordinates. I plot this on a geographic axes. I want to rotate it and end up with a new rotated set of (lat,lon) coordinates. I don’t want a filled polygon, but perhaps I could adjust the transparency if that’s the only way (such as patch). Here is what I tried, but not sure it works accurately due to the oblate earth surface. I prefer not to use Mapping Toolbox, but just core Matlab.
geoplot(lat,lon,’k-‘)
polyin = polyshape([lat’,lon’]);
refPoint = [refLat, refLon];
polyout = rotate(polyin, angleDeg, refPoint);
lat = [polyout.Vertices(:,1); polyout.Vertices(1,1)];
lon = [polyout.Vertices(:,2); polyout.Vertices(1,2)];
geoplot(lat,lon,’b–‘) rotate, polygon MATLAB Answers — New Questions
Is it posibble to import a simulink model into Unreal Engine simulation ?
Hi,
I’m trying to create a simulation of a self-driving car in Unreal Engine with Simulink modeling the dynamics and control logic. It is easy to use UE scenes in Simulink, but I’m wondering if it’s possible to compile the Simulink model into the Unreal Engine project. The simulation would be developed in Unreal Engine, and I need the logic from Simulink to be imported into the UE project.
Is there any easy way to do this, except for compiling the Simulink model into C++ and incorporating it by hand into UE project?
Thanks for the help.Hi,
I’m trying to create a simulation of a self-driving car in Unreal Engine with Simulink modeling the dynamics and control logic. It is easy to use UE scenes in Simulink, but I’m wondering if it’s possible to compile the Simulink model into the Unreal Engine project. The simulation would be developed in Unreal Engine, and I need the logic from Simulink to be imported into the UE project.
Is there any easy way to do this, except for compiling the Simulink model into C++ and incorporating it by hand into UE project?
Thanks for the help. Hi,
I’m trying to create a simulation of a self-driving car in Unreal Engine with Simulink modeling the dynamics and control logic. It is easy to use UE scenes in Simulink, but I’m wondering if it’s possible to compile the Simulink model into the Unreal Engine project. The simulation would be developed in Unreal Engine, and I need the logic from Simulink to be imported into the UE project.
Is there any easy way to do this, except for compiling the Simulink model into C++ and incorporating it by hand into UE project?
Thanks for the help. unreal engine, simulink, self-driving MATLAB Answers — New Questions
dicomreadVolume ‘Directory was not readable’ error
I am trying to load in a zip folder with dcm files into MATLAB. However, when I use the dicomreadVolume function I am getting an error. I tried unzipping it directly in my file explorer. How can I fix this error?
ctScan = dicomreadVolume(‘Spine_CT.dcm’);
Error using dicomreadVolume>getFilenames
Directory was not readable.
Error in dicomreadVolume (line 11)
filenames = getFilenames(inputSource);
Error in untitled (line 1)
ctScan = dicomreadVolume(‘Spine_CT.dcm’);I am trying to load in a zip folder with dcm files into MATLAB. However, when I use the dicomreadVolume function I am getting an error. I tried unzipping it directly in my file explorer. How can I fix this error?
ctScan = dicomreadVolume(‘Spine_CT.dcm’);
Error using dicomreadVolume>getFilenames
Directory was not readable.
Error in dicomreadVolume (line 11)
filenames = getFilenames(inputSource);
Error in untitled (line 1)
ctScan = dicomreadVolume(‘Spine_CT.dcm’); I am trying to load in a zip folder with dcm files into MATLAB. However, when I use the dicomreadVolume function I am getting an error. I tried unzipping it directly in my file explorer. How can I fix this error?
ctScan = dicomreadVolume(‘Spine_CT.dcm’);
Error using dicomreadVolume>getFilenames
Directory was not readable.
Error in dicomreadVolume (line 11)
filenames = getFilenames(inputSource);
Error in untitled (line 1)
ctScan = dicomreadVolume(‘Spine_CT.dcm’); dicom, dicomread, dicomreadvolume, error MATLAB Answers — New Questions
How can I do intermittent logging with real-time File Log blocks to generate multiple log files and SDI runs?
I run my Simulink Real-Time (SLRT) simulation for multiple days to conduct several experiments using my Speedgoat hardware. I want to start and stop file logging and have separate runs for each experiment when importing the file logs into Simulation Data Inspector (SDI). Ideally, I would like to import completed experiment runs while running a new experiment and recording new data.I run my Simulink Real-Time (SLRT) simulation for multiple days to conduct several experiments using my Speedgoat hardware. I want to start and stop file logging and have separate runs for each experiment when importing the file logs into Simulation Data Inspector (SDI). Ideally, I would like to import completed experiment runs while running a new experiment and recording new data. I run my Simulink Real-Time (SLRT) simulation for multiple days to conduct several experiments using my Speedgoat hardware. I want to start and stop file logging and have separate runs for each experiment when importing the file logs into Simulation Data Inspector (SDI). Ideally, I would like to import completed experiment runs while running a new experiment and recording new data. filelog, segmentation, intermittent, trigger, experiments, data, logging, long-term, speedgoat MATLAB Answers — New Questions
Why is this autoencoder only predicting a single output regardless of input when using min-max scaling?
Key questions:
Why does a network predict a specific value for the output regardless of input as if the input data had no information relevant to prediction?
Why does replacing min-max scaling with standard scaling fix this, at least occassionally?
The problem background: I am trying to train a simple image autoencoder, but I keep getting networks that only output a single image regardless of the input. Taking the difference between each output image reveals they are all exactly the same. Googling this issue, I saw a stack overflow post that this often arises with improperly dimensioned loss functions. I also saw folks mentioning issues with using the sigmoid loss function for autoencoders, but the explanations as to why never surpass guesswork. I changed the scaling from min-max scaling to standard scaling and was able to obtain a network that breaks out of the single-prediction behavior, but without understanding why, I will have no recourse but trial-and-error if it breaks again.
Notes on dimensioning loss functions: When calculating the loss between a batch of images of shape [imgDim, imgDim, 1, batchSize] the mse loss function outputs a loss of dimension [1,1,1,batchSize], but this loss function has produced defective results under min-max scaling, such as the aforementioned degeneration to a single output, as well as an initial loss three orders of magnitude above the inputs and outputs scaled to the range [0,1]. To be clear, I don’t mean the learning is unstable, I mean that the absolute values of the loss are absurd.
I tried to write my own loss function that reports a scalar value, but I encountered the same degeneration to a single prediction independent of input. I then wrote a version that reports an error tensor of the same shape as @mse, but this threw an error listed below, after the custom loss function in question.
% Version that reports a scalar
function meanAbsErr = myMae(prediction, target)
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), ‘all’);
end
% Version that reports [1,1,1,batchSize]
function meanAbsErr = myMae(prediction, target)
inDims = size(prediction);
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), 1);
outDims = ones(1,length(inDims)); outDims(end) = inDims(end);
meanAbsErr = reshape(meanAbsErr, outDims);
end
Value to differentiate is non-scalar. It must be a traced real dlarray scalar.
Error in mathworksDebug>modelLoss (line 213)
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
Error in mathworksDebug (line 134)
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
Notes on scaling
I wrote a custom scaling function that executes the same behavior as rescale except that it reports the obtained extrema to use in scaling and de-scaling unseen data.
% Min-max scaling between [lb, ub]
function [scaled,smin,smax] = myRescale(varargin)
datastruct = varargin{1}; lb = varargin{2}; ub = varargin{3};
if length(varargin) <= 3
smin = min(datastruct(:)); smax = max(datastruct(:));
else
smin = varargin{4}; smax = varargin{5};
end
scaled = (datastruct – smin) / (smax – smin) * (ub – lb) + lb;
end
% Invert scaling
function unscaled = myDescale(scaled, lb, ub, smin, smax)
unscaled = (scaled + lb ) * (smax – smin) ./ (ub – lb) + smin;
end
% Converts the data to z-scores
function [standard, center, stddev] = myStandardize(varargin)
datastruct = varargin{1};
if length(varargin) == 1
center = mean(datastruct(:)); stddev = std(datastruct(:));
else
center = varargin{2}; stddev = varargin{3};
end
standard = (datastruct – center) / stddev;
end
% Converts z-scores back to the data’s scale
function destandard = myDestandardize(datastruct, center, stddev)
destandard = datastruct * stddev + center;
end
In the following code, I have removed the validation set to reduce bloat.
% % I intend to regularize the latent space of this autoencoder to be a
% classify images once it can accomplish basic reconstruction. I made this note so
% it’s clear what’s going on with the custom losses and so forth.
xTrain = digitTrain4DArrayData;
xTest = digitTest4DArrayData;
%% Scaling that does not work
% Min-max scaling
xlb = 0; xub=1;
[xTrain, xTrainMin, xTrainMax] = myRescale(xTrain, xl, xub);
xTest = myRescale(xTest, xTrainMin, xTrainMax);
%% Scaling that works, at least occasionally
xTest = myStandardize(xTest, xTrainCenter, xTrainStd);
ntrain = size(xDev,4);
IMG_DIM = size(xDev, 1);N_CHANNELS=size(xDev, 3);
OUT_CHANNELS = min(size(tTrain,1), 64);
numLatentChannels = OUT_CHANNELS;
imageSize = [28 28 1];
%% Layer definitions
% Encoder layer
layersE = [
imageInputLayer(imageSize,Normalization="none")
convolution2dLayer(3,32,Padding="same",Stride=2)
reluLayer
convolution2dLayer(3,64,Padding="same",Stride=2)
reluLayer
fullyConnectedLayer(numLatentChannels)
tanhLayer(Name=’latent’)];
% Latent projection
projectionSize = [7 7 64]; enc_dim = projectionSize(1);
numInputChannels = imageSize(3);
% Decoder
layersD = [
featureInputLayer(numLatentChannels)
projectAndReshapeLayer(projectionSize)
transposedConv2dLayer(3,64,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,32,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,numInputChannels,Cropping="same")
sigmoidLayer(‘Output’)
];
netE = dlnetwork(layersE);
netD = dlnetwork(layersD);
%% Training Parameters
numEpochs = 150;
miniBatchSize = 20;
learnRate = 1e-3;
dsXTrain = arrayDatastore(xTrain,IterationDimension=4);
dstTrain = arrayDatastore(tTrain,IterationDimension=2);
numOutputs = 2;
dsTrain = combine(dsXTrain, dstTrain);
mbq = minibatchqueue(dsTrain,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFormat=["SSCB", "CB"], …
MiniBatchFcn=@preprocessMiniBatch,…
PartialMiniBatch="return");
%Initialize the parameters for the Adam solver.
trailingAvgE = [];
trailingAvgSqE = [];
trailingAvgD = [];
trailingAvgSqD = [];
%Calculate the total number of iterations for the training progress monitor
numIterationsPerEpoch = ceil(ntrain / miniBatchSize);
numIterations = numEpochs * numIterationsPerEpoch;
epoch = 0;
iteration = 0;
%Initialize the training progress monitor.
monitor = trainingProgressMonitor( …
Metrics=["TrainingLoss"], …
Info=["Epoch", "LearningRate"], …
XLabel="Iteration");
%% Training
while epoch < numEpochs && ~monitor.Stop
epoch = epoch + 1;
% Shuffle data.
shuffle(mbq);
% Loop over mini-batches.
while hasdata(mbq) && ~monitor.Stop
iteration = iteration + 1;
% Read mini-batch of data.
[X, Ztarget] = next(mbq);
% Evaluate loss and gradients.
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
% Update learnable parameters.
[netE,trailingAvgE,trailingAvgSqE] = adamupdate(netE, …
gradientsE,trailingAvgE,trailingAvgSqE,iteration,learnRate);
[netD, trailingAvgD, trailingAvgSqD] = adamupdate(netD, …
gradientsD,trailingAvgD,trailingAvgSqD,iteration,learnRate);
updateInfo(monitor, …
LearningRate=learnRate, …
Epoch=string(epoch) + " of " + string(numEpochs));
recordMetrics(monitor,iteration, …
TrainingLoss=loss);
monitor.Progress = 100*iteration/numIterations;
end
end
%% Testing
dsTest = combine(arrayDatastore(xTest,IterationDimension=4),…
arrayDatastore(tTest,IterationDimension=2));
numOutputs = 2;
mbqTest = minibatchqueue(dsTest,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFcn=@preprocessMiniBatch, …
MiniBatchFormat="SSCB");
[YTest, ZTest] = modelPredictions(netE,netD,mbqTest);
reconerr = mean(flatten(xTest-YTest),1);
figure
histogram(reconerr)
xlabel("Reconstruction Error")
ylabel("Frequency")
title("Test Data")
numImages = 64;
ndisplay = 10;
figure
I = imtile(YTest(:,:,:,1:numImages));
imshow(I)
title("Reconstructed Images")
%% Functions
function [loss,gradientsE,gradientsD] = modelLoss(netE,netD,X,Ztarget)
% Forward through encoder.
Z = forward(netE,X);
% Forward through decoder.
Xrecon = forward(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
end
function loss = regularizedLoss(Xrecon,X,Z,Ztarget)
% Image Reconstruction loss.
reconstructionLoss = mse(Xrecon, X);
% Regularized Loss
%regLoss = mse(Z, Ztarget);
% Combined loss.
loss = reconstructionLoss;% + 0.0*regLoss;
end
function [Xrecon, Zpred] = modelPredictions(netE,netD,mbq)
Xrecon = [];
Zpred = [];
% Loop over mini-batches.
while hasdata(mbq)
X = next(mbq);
% Pass through encoder
Z = predict(netE,X);
% Pass through decoder to get reconstructed images
XGenerated = predict(netD,Z);
% Extract and concatenate predictions.
Xrecon = cat(4,Xrecon,extractdata(XGenerated));
Zpred = cat(2,Zpred,extractdata(Z));
end
end
function loss = assessLoss(netE, netD, X, Ztarget)
% Forward through encoder.
Z = predict(netE,X);
% Forward through decoder.
Xrecon = predict(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
end
function [X, Ztarget] = preprocessMiniBatch(Xcell, tCell)
% Concatenate.
X = cat(4,Xcell{:});
% Concatenate.
Ztarget = cat(2,tCell{:});
endKey questions:
Why does a network predict a specific value for the output regardless of input as if the input data had no information relevant to prediction?
Why does replacing min-max scaling with standard scaling fix this, at least occassionally?
The problem background: I am trying to train a simple image autoencoder, but I keep getting networks that only output a single image regardless of the input. Taking the difference between each output image reveals they are all exactly the same. Googling this issue, I saw a stack overflow post that this often arises with improperly dimensioned loss functions. I also saw folks mentioning issues with using the sigmoid loss function for autoencoders, but the explanations as to why never surpass guesswork. I changed the scaling from min-max scaling to standard scaling and was able to obtain a network that breaks out of the single-prediction behavior, but without understanding why, I will have no recourse but trial-and-error if it breaks again.
Notes on dimensioning loss functions: When calculating the loss between a batch of images of shape [imgDim, imgDim, 1, batchSize] the mse loss function outputs a loss of dimension [1,1,1,batchSize], but this loss function has produced defective results under min-max scaling, such as the aforementioned degeneration to a single output, as well as an initial loss three orders of magnitude above the inputs and outputs scaled to the range [0,1]. To be clear, I don’t mean the learning is unstable, I mean that the absolute values of the loss are absurd.
I tried to write my own loss function that reports a scalar value, but I encountered the same degeneration to a single prediction independent of input. I then wrote a version that reports an error tensor of the same shape as @mse, but this threw an error listed below, after the custom loss function in question.
% Version that reports a scalar
function meanAbsErr = myMae(prediction, target)
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), ‘all’);
end
% Version that reports [1,1,1,batchSize]
function meanAbsErr = myMae(prediction, target)
inDims = size(prediction);
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), 1);
outDims = ones(1,length(inDims)); outDims(end) = inDims(end);
meanAbsErr = reshape(meanAbsErr, outDims);
end
Value to differentiate is non-scalar. It must be a traced real dlarray scalar.
Error in mathworksDebug>modelLoss (line 213)
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
Error in mathworksDebug (line 134)
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
Notes on scaling
I wrote a custom scaling function that executes the same behavior as rescale except that it reports the obtained extrema to use in scaling and de-scaling unseen data.
% Min-max scaling between [lb, ub]
function [scaled,smin,smax] = myRescale(varargin)
datastruct = varargin{1}; lb = varargin{2}; ub = varargin{3};
if length(varargin) <= 3
smin = min(datastruct(:)); smax = max(datastruct(:));
else
smin = varargin{4}; smax = varargin{5};
end
scaled = (datastruct – smin) / (smax – smin) * (ub – lb) + lb;
end
% Invert scaling
function unscaled = myDescale(scaled, lb, ub, smin, smax)
unscaled = (scaled + lb ) * (smax – smin) ./ (ub – lb) + smin;
end
% Converts the data to z-scores
function [standard, center, stddev] = myStandardize(varargin)
datastruct = varargin{1};
if length(varargin) == 1
center = mean(datastruct(:)); stddev = std(datastruct(:));
else
center = varargin{2}; stddev = varargin{3};
end
standard = (datastruct – center) / stddev;
end
% Converts z-scores back to the data’s scale
function destandard = myDestandardize(datastruct, center, stddev)
destandard = datastruct * stddev + center;
end
In the following code, I have removed the validation set to reduce bloat.
% % I intend to regularize the latent space of this autoencoder to be a
% classify images once it can accomplish basic reconstruction. I made this note so
% it’s clear what’s going on with the custom losses and so forth.
xTrain = digitTrain4DArrayData;
xTest = digitTest4DArrayData;
%% Scaling that does not work
% Min-max scaling
xlb = 0; xub=1;
[xTrain, xTrainMin, xTrainMax] = myRescale(xTrain, xl, xub);
xTest = myRescale(xTest, xTrainMin, xTrainMax);
%% Scaling that works, at least occasionally
xTest = myStandardize(xTest, xTrainCenter, xTrainStd);
ntrain = size(xDev,4);
IMG_DIM = size(xDev, 1);N_CHANNELS=size(xDev, 3);
OUT_CHANNELS = min(size(tTrain,1), 64);
numLatentChannels = OUT_CHANNELS;
imageSize = [28 28 1];
%% Layer definitions
% Encoder layer
layersE = [
imageInputLayer(imageSize,Normalization="none")
convolution2dLayer(3,32,Padding="same",Stride=2)
reluLayer
convolution2dLayer(3,64,Padding="same",Stride=2)
reluLayer
fullyConnectedLayer(numLatentChannels)
tanhLayer(Name=’latent’)];
% Latent projection
projectionSize = [7 7 64]; enc_dim = projectionSize(1);
numInputChannels = imageSize(3);
% Decoder
layersD = [
featureInputLayer(numLatentChannels)
projectAndReshapeLayer(projectionSize)
transposedConv2dLayer(3,64,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,32,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,numInputChannels,Cropping="same")
sigmoidLayer(‘Output’)
];
netE = dlnetwork(layersE);
netD = dlnetwork(layersD);
%% Training Parameters
numEpochs = 150;
miniBatchSize = 20;
learnRate = 1e-3;
dsXTrain = arrayDatastore(xTrain,IterationDimension=4);
dstTrain = arrayDatastore(tTrain,IterationDimension=2);
numOutputs = 2;
dsTrain = combine(dsXTrain, dstTrain);
mbq = minibatchqueue(dsTrain,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFormat=["SSCB", "CB"], …
MiniBatchFcn=@preprocessMiniBatch,…
PartialMiniBatch="return");
%Initialize the parameters for the Adam solver.
trailingAvgE = [];
trailingAvgSqE = [];
trailingAvgD = [];
trailingAvgSqD = [];
%Calculate the total number of iterations for the training progress monitor
numIterationsPerEpoch = ceil(ntrain / miniBatchSize);
numIterations = numEpochs * numIterationsPerEpoch;
epoch = 0;
iteration = 0;
%Initialize the training progress monitor.
monitor = trainingProgressMonitor( …
Metrics=["TrainingLoss"], …
Info=["Epoch", "LearningRate"], …
XLabel="Iteration");
%% Training
while epoch < numEpochs && ~monitor.Stop
epoch = epoch + 1;
% Shuffle data.
shuffle(mbq);
% Loop over mini-batches.
while hasdata(mbq) && ~monitor.Stop
iteration = iteration + 1;
% Read mini-batch of data.
[X, Ztarget] = next(mbq);
% Evaluate loss and gradients.
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
% Update learnable parameters.
[netE,trailingAvgE,trailingAvgSqE] = adamupdate(netE, …
gradientsE,trailingAvgE,trailingAvgSqE,iteration,learnRate);
[netD, trailingAvgD, trailingAvgSqD] = adamupdate(netD, …
gradientsD,trailingAvgD,trailingAvgSqD,iteration,learnRate);
updateInfo(monitor, …
LearningRate=learnRate, …
Epoch=string(epoch) + " of " + string(numEpochs));
recordMetrics(monitor,iteration, …
TrainingLoss=loss);
monitor.Progress = 100*iteration/numIterations;
end
end
%% Testing
dsTest = combine(arrayDatastore(xTest,IterationDimension=4),…
arrayDatastore(tTest,IterationDimension=2));
numOutputs = 2;
mbqTest = minibatchqueue(dsTest,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFcn=@preprocessMiniBatch, …
MiniBatchFormat="SSCB");
[YTest, ZTest] = modelPredictions(netE,netD,mbqTest);
reconerr = mean(flatten(xTest-YTest),1);
figure
histogram(reconerr)
xlabel("Reconstruction Error")
ylabel("Frequency")
title("Test Data")
numImages = 64;
ndisplay = 10;
figure
I = imtile(YTest(:,:,:,1:numImages));
imshow(I)
title("Reconstructed Images")
%% Functions
function [loss,gradientsE,gradientsD] = modelLoss(netE,netD,X,Ztarget)
% Forward through encoder.
Z = forward(netE,X);
% Forward through decoder.
Xrecon = forward(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
end
function loss = regularizedLoss(Xrecon,X,Z,Ztarget)
% Image Reconstruction loss.
reconstructionLoss = mse(Xrecon, X);
% Regularized Loss
%regLoss = mse(Z, Ztarget);
% Combined loss.
loss = reconstructionLoss;% + 0.0*regLoss;
end
function [Xrecon, Zpred] = modelPredictions(netE,netD,mbq)
Xrecon = [];
Zpred = [];
% Loop over mini-batches.
while hasdata(mbq)
X = next(mbq);
% Pass through encoder
Z = predict(netE,X);
% Pass through decoder to get reconstructed images
XGenerated = predict(netD,Z);
% Extract and concatenate predictions.
Xrecon = cat(4,Xrecon,extractdata(XGenerated));
Zpred = cat(2,Zpred,extractdata(Z));
end
end
function loss = assessLoss(netE, netD, X, Ztarget)
% Forward through encoder.
Z = predict(netE,X);
% Forward through decoder.
Xrecon = predict(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
end
function [X, Ztarget] = preprocessMiniBatch(Xcell, tCell)
% Concatenate.
X = cat(4,Xcell{:});
% Concatenate.
Ztarget = cat(2,tCell{:});
end Key questions:
Why does a network predict a specific value for the output regardless of input as if the input data had no information relevant to prediction?
Why does replacing min-max scaling with standard scaling fix this, at least occassionally?
The problem background: I am trying to train a simple image autoencoder, but I keep getting networks that only output a single image regardless of the input. Taking the difference between each output image reveals they are all exactly the same. Googling this issue, I saw a stack overflow post that this often arises with improperly dimensioned loss functions. I also saw folks mentioning issues with using the sigmoid loss function for autoencoders, but the explanations as to why never surpass guesswork. I changed the scaling from min-max scaling to standard scaling and was able to obtain a network that breaks out of the single-prediction behavior, but without understanding why, I will have no recourse but trial-and-error if it breaks again.
Notes on dimensioning loss functions: When calculating the loss between a batch of images of shape [imgDim, imgDim, 1, batchSize] the mse loss function outputs a loss of dimension [1,1,1,batchSize], but this loss function has produced defective results under min-max scaling, such as the aforementioned degeneration to a single output, as well as an initial loss three orders of magnitude above the inputs and outputs scaled to the range [0,1]. To be clear, I don’t mean the learning is unstable, I mean that the absolute values of the loss are absurd.
I tried to write my own loss function that reports a scalar value, but I encountered the same degeneration to a single prediction independent of input. I then wrote a version that reports an error tensor of the same shape as @mse, but this threw an error listed below, after the custom loss function in question.
% Version that reports a scalar
function meanAbsErr = myMae(prediction, target)
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), ‘all’);
end
% Version that reports [1,1,1,batchSize]
function meanAbsErr = myMae(prediction, target)
inDims = size(prediction);
meanAbsErr = mean(abs(flatten(prediction) – flatten(target)), 1);
outDims = ones(1,length(inDims)); outDims(end) = inDims(end);
meanAbsErr = reshape(meanAbsErr, outDims);
end
Value to differentiate is non-scalar. It must be a traced real dlarray scalar.
Error in mathworksDebug>modelLoss (line 213)
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
Error in mathworksDebug (line 134)
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
Notes on scaling
I wrote a custom scaling function that executes the same behavior as rescale except that it reports the obtained extrema to use in scaling and de-scaling unseen data.
% Min-max scaling between [lb, ub]
function [scaled,smin,smax] = myRescale(varargin)
datastruct = varargin{1}; lb = varargin{2}; ub = varargin{3};
if length(varargin) <= 3
smin = min(datastruct(:)); smax = max(datastruct(:));
else
smin = varargin{4}; smax = varargin{5};
end
scaled = (datastruct – smin) / (smax – smin) * (ub – lb) + lb;
end
% Invert scaling
function unscaled = myDescale(scaled, lb, ub, smin, smax)
unscaled = (scaled + lb ) * (smax – smin) ./ (ub – lb) + smin;
end
% Converts the data to z-scores
function [standard, center, stddev] = myStandardize(varargin)
datastruct = varargin{1};
if length(varargin) == 1
center = mean(datastruct(:)); stddev = std(datastruct(:));
else
center = varargin{2}; stddev = varargin{3};
end
standard = (datastruct – center) / stddev;
end
% Converts z-scores back to the data’s scale
function destandard = myDestandardize(datastruct, center, stddev)
destandard = datastruct * stddev + center;
end
In the following code, I have removed the validation set to reduce bloat.
% % I intend to regularize the latent space of this autoencoder to be a
% classify images once it can accomplish basic reconstruction. I made this note so
% it’s clear what’s going on with the custom losses and so forth.
xTrain = digitTrain4DArrayData;
xTest = digitTest4DArrayData;
%% Scaling that does not work
% Min-max scaling
xlb = 0; xub=1;
[xTrain, xTrainMin, xTrainMax] = myRescale(xTrain, xl, xub);
xTest = myRescale(xTest, xTrainMin, xTrainMax);
%% Scaling that works, at least occasionally
xTest = myStandardize(xTest, xTrainCenter, xTrainStd);
ntrain = size(xDev,4);
IMG_DIM = size(xDev, 1);N_CHANNELS=size(xDev, 3);
OUT_CHANNELS = min(size(tTrain,1), 64);
numLatentChannels = OUT_CHANNELS;
imageSize = [28 28 1];
%% Layer definitions
% Encoder layer
layersE = [
imageInputLayer(imageSize,Normalization="none")
convolution2dLayer(3,32,Padding="same",Stride=2)
reluLayer
convolution2dLayer(3,64,Padding="same",Stride=2)
reluLayer
fullyConnectedLayer(numLatentChannels)
tanhLayer(Name=’latent’)];
% Latent projection
projectionSize = [7 7 64]; enc_dim = projectionSize(1);
numInputChannels = imageSize(3);
% Decoder
layersD = [
featureInputLayer(numLatentChannels)
projectAndReshapeLayer(projectionSize)
transposedConv2dLayer(3,64,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,32,Cropping="same",Stride=2)
reluLayer
transposedConv2dLayer(3,numInputChannels,Cropping="same")
sigmoidLayer(‘Output’)
];
netE = dlnetwork(layersE);
netD = dlnetwork(layersD);
%% Training Parameters
numEpochs = 150;
miniBatchSize = 20;
learnRate = 1e-3;
dsXTrain = arrayDatastore(xTrain,IterationDimension=4);
dstTrain = arrayDatastore(tTrain,IterationDimension=2);
numOutputs = 2;
dsTrain = combine(dsXTrain, dstTrain);
mbq = minibatchqueue(dsTrain,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFormat=["SSCB", "CB"], …
MiniBatchFcn=@preprocessMiniBatch,…
PartialMiniBatch="return");
%Initialize the parameters for the Adam solver.
trailingAvgE = [];
trailingAvgSqE = [];
trailingAvgD = [];
trailingAvgSqD = [];
%Calculate the total number of iterations for the training progress monitor
numIterationsPerEpoch = ceil(ntrain / miniBatchSize);
numIterations = numEpochs * numIterationsPerEpoch;
epoch = 0;
iteration = 0;
%Initialize the training progress monitor.
monitor = trainingProgressMonitor( …
Metrics=["TrainingLoss"], …
Info=["Epoch", "LearningRate"], …
XLabel="Iteration");
%% Training
while epoch < numEpochs && ~monitor.Stop
epoch = epoch + 1;
% Shuffle data.
shuffle(mbq);
% Loop over mini-batches.
while hasdata(mbq) && ~monitor.Stop
iteration = iteration + 1;
% Read mini-batch of data.
[X, Ztarget] = next(mbq);
% Evaluate loss and gradients.
[loss,gradientsE,gradientsD] = dlfeval(@modelLoss,netE,netD,X,Ztarget);
% Update learnable parameters.
[netE,trailingAvgE,trailingAvgSqE] = adamupdate(netE, …
gradientsE,trailingAvgE,trailingAvgSqE,iteration,learnRate);
[netD, trailingAvgD, trailingAvgSqD] = adamupdate(netD, …
gradientsD,trailingAvgD,trailingAvgSqD,iteration,learnRate);
updateInfo(monitor, …
LearningRate=learnRate, …
Epoch=string(epoch) + " of " + string(numEpochs));
recordMetrics(monitor,iteration, …
TrainingLoss=loss);
monitor.Progress = 100*iteration/numIterations;
end
end
%% Testing
dsTest = combine(arrayDatastore(xTest,IterationDimension=4),…
arrayDatastore(tTest,IterationDimension=2));
numOutputs = 2;
mbqTest = minibatchqueue(dsTest,numOutputs, …
MiniBatchSize = miniBatchSize, …
MiniBatchFcn=@preprocessMiniBatch, …
MiniBatchFormat="SSCB");
[YTest, ZTest] = modelPredictions(netE,netD,mbqTest);
reconerr = mean(flatten(xTest-YTest),1);
figure
histogram(reconerr)
xlabel("Reconstruction Error")
ylabel("Frequency")
title("Test Data")
numImages = 64;
ndisplay = 10;
figure
I = imtile(YTest(:,:,:,1:numImages));
imshow(I)
title("Reconstructed Images")
%% Functions
function [loss,gradientsE,gradientsD] = modelLoss(netE,netD,X,Ztarget)
% Forward through encoder.
Z = forward(netE,X);
% Forward through decoder.
Xrecon = forward(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
[gradientsE,gradientsD] = dlgradient(loss,netE.Learnables,netD.Learnables);
end
function loss = regularizedLoss(Xrecon,X,Z,Ztarget)
% Image Reconstruction loss.
reconstructionLoss = mse(Xrecon, X);
% Regularized Loss
%regLoss = mse(Z, Ztarget);
% Combined loss.
loss = reconstructionLoss;% + 0.0*regLoss;
end
function [Xrecon, Zpred] = modelPredictions(netE,netD,mbq)
Xrecon = [];
Zpred = [];
% Loop over mini-batches.
while hasdata(mbq)
X = next(mbq);
% Pass through encoder
Z = predict(netE,X);
% Pass through decoder to get reconstructed images
XGenerated = predict(netD,Z);
% Extract and concatenate predictions.
Xrecon = cat(4,Xrecon,extractdata(XGenerated));
Zpred = cat(2,Zpred,extractdata(Z));
end
end
function loss = assessLoss(netE, netD, X, Ztarget)
% Forward through encoder.
Z = predict(netE,X);
% Forward through decoder.
Xrecon = predict(netD,Z);
% Calculate loss and gradients.
loss = regularizedLoss(Xrecon,X,Z,Ztarget);
end
function [X, Ztarget] = preprocessMiniBatch(Xcell, tCell)
% Concatenate.
X = cat(4,Xcell{:});
% Concatenate.
Ztarget = cat(2,tCell{:});
end autoencoder, deep learning, scaling, activation functions MATLAB Answers — New Questions
I can’t model a piezoelectric transducer
Hello to all,
I am currently trying to model a piezoelectric sensor which transforms mechanical energy into electrical energy with Simulink but I encounter some difficulties …
Here is a snapshot of my current montage (not functional):
Could someone help me solve this problem …?
Thank you in advance,Hello to all,
I am currently trying to model a piezoelectric sensor which transforms mechanical energy into electrical energy with Simulink but I encounter some difficulties …
Here is a snapshot of my current montage (not functional):
Could someone help me solve this problem …?
Thank you in advance, Hello to all,
I am currently trying to model a piezoelectric sensor which transforms mechanical energy into electrical energy with Simulink but I encounter some difficulties …
Here is a snapshot of my current montage (not functional):
Could someone help me solve this problem …?
Thank you in advance, matlab, simulink, model, piezo MATLAB Answers — New Questions
How can I create new runs & discard data from SDI while live streaming signals from my Speedgoat target?
I am doing iterative experiments with my Speedgoat hardware where I would like to start and stop signal monitoring during the simulation. Before 2020b, I used Target Scopes to trace & import the data, then removed the Target Scope after every iteration to clear the buffer. Target Scopes were removed in R2020b.
For accomplishing the same workflow in R2020b and beyond, I am trying to use instruments to start/stop streaming signals to Simulation Data Inspector (SDI) during a running simulation. However, all the data will be shown in the same run in SDI. This makes it hard to visualize the data in SDI, and I cannot clear the data from SDI between the iterations.
How can I achieve my desired workflow in Simulink Real-Time R2020b and beyond?I am doing iterative experiments with my Speedgoat hardware where I would like to start and stop signal monitoring during the simulation. Before 2020b, I used Target Scopes to trace & import the data, then removed the Target Scope after every iteration to clear the buffer. Target Scopes were removed in R2020b.
For accomplishing the same workflow in R2020b and beyond, I am trying to use instruments to start/stop streaming signals to Simulation Data Inspector (SDI) during a running simulation. However, all the data will be shown in the same run in SDI. This makes it hard to visualize the data in SDI, and I cannot clear the data from SDI between the iterations.
How can I achieve my desired workflow in Simulink Real-Time R2020b and beyond? I am doing iterative experiments with my Speedgoat hardware where I would like to start and stop signal monitoring during the simulation. Before 2020b, I used Target Scopes to trace & import the data, then removed the Target Scope after every iteration to clear the buffer. Target Scopes were removed in R2020b.
For accomplishing the same workflow in R2020b and beyond, I am trying to use instruments to start/stop streaming signals to Simulation Data Inspector (SDI) during a running simulation. However, all the data will be shown in the same run in SDI. This makes it hard to visualize the data in SDI, and I cannot clear the data from SDI between the iterations.
How can I achieve my desired workflow in Simulink Real-Time R2020b and beyond? slrt, sdi, speedgoat, streaming, start, recording, stop MATLAB Answers — New Questions