The topic recently came up in a MATLAB Central Answers forum thread, where community members discussed how to programmatically control when the end user can close a custom app. Imagine you need to prevent app closure during a critical process but want to allow the end user to close the app afterwards. This article will guide you through the steps to add this behavior to your app.
A demo is attached containing an app with a state button that, when enabled, disables the ability to close the app.
Steps
1. Add a property that stores the state of the closure as a scalar logical value. In this example, I named the property closeEnabled. The default value in this example is true, meaning that closing is enabled. -- How to add a property to an app in app designer
properties (Access = private)
closeEnabled = true % Flag that controls ability to close app
end
2. Add a CloseRequest function to the app figure. This function is called any time there is an attempt to close the app. Within the CloseRequest function, add a condition that deletes the app when closure is enabled. -- How to add a CloseRequest function to an app figure in app designer
function UIFigureCloseRequest(app, event)
if app.closeEnabled
delete(app)
end
3. Toggle the value of the closeEnabled property as needed in your code. Imagine you have a "Process" button that initiates a process where it is crucial for the app to remain open. Set the closeEnabled flag to false (closure is disabled) at the beginning of the button's callback function and then set it to true at the end (closure is enabled).
function ProcessButtonPress(app, event)
app.closeEnabled = false;
% MY PROCESS CODE
app.closeEnabled = true;
end
Handling Errors: There is one trap to keep in mind in the example above. What if something in the callback function breaks before the app.closeEnabled is returned to true? That leaves the app in a bad state where closure is blocked. A pro move would be to use a cleanupObj to manage returning the property to true. In the example below, the task to return the closeEnabled property to true is managed by the cleanup object, which will execute that command when execution is terminated in the ProcessButtonPress function—whether execution was terminated by error or by gracefully exiting the function.
function ProcessButtonPress(app, event)
app.closeEnabled = false;
cleanupClosure = onCleanup(@()set(app,'closeEnabled',true));
% MY CODE
end
Force Closure: If the CloseRequest function is preventing an app from closing, here are a couple of ways to force a closure.
  1. If you have the app's handle, use delete(app) or close(app,'force'). This will also work on the app's figure handle.
  2. If you do not have the app's handle, you can use close('all','force') to close all figures or use findall(groot,'type','figure') to find the app's figure handle.

Aochen Xiao
Aochen Xiao
Ultima attività circa 23 ore fa

It is April 3, 2025 now. Where is the MATLAB 2025a?
This topic is for discussing highlights to the current R2025a Pre-release.
Hi,
We are looking for users of Simulink who also work with the Vehicle Network toolbox to attend a usability session. This wil be a 2 hour session and will offer $100 compensation.
If you are interested, please answer the questions below and send them to: usabilityrecruiting@mathworks.com
In the past 2 years, how often have you worked with ARXML (AUTOSAR XML) files in vehicle network communication?
a. At least 3-5 days per week
b. Once or twice a week
c. A few times a month
d. Once a month or less
e. Never
-
3. Have you worked with automotive ethernet in the past?
a. Yes
b. No
-
4. Which of the following best describe your experience with Simulink? (select all that apply)
Study Screener Q4
a. I have used CAN/ CAN FD blocks (https://www.mathworks.com/help/vnt/can-simulink-communication.html)
b. I have used Simulink Buses
c. I have used Simulink Data Dictionaries
d. Other
-
Thank you!
Elaine
Andrew Janke
Andrew Janke
Ultima attività il 29 Apr 2025 alle 14:07

Let's say MathWorks decides to create a MATLAB X release, which takes a big one-time breaking change that abandons back-compatibility and creates a more modern MATLAB language, ditching the unfortunate stuff that's around for historical reasons. What would you like to see in it?
I'm thinking stuff like syntax and semantics tweaks, changes to function behavior and interfaces in the standard library and Toolboxes, and so on.
(The "X" is for major version 10, like in "OS X". Matlab is still on version 9.x even though we use "R20xxa" release names now.)
What should you post where?
Wishlist threads (#1 #2 #3 #4 #5): bugs and feature requests for Matlab Answers
Frustation threads (#1 #2): frustrations about usage and capabilities of Matlab itself
Missing feature threads (#1 #2): features that you whish Matlab would have had
Next Gen threads (#1): features that would break compatibility with previous versions, but would be nice to have
@anyone posting a new thread when the last one gets too large (about 50 answers seems a reasonable limit per thread), please update this list in all last threads. (if you don't have editing privileges, just post a comment asking someone to do the edit)
If you are interested in this session, just send an email with the answers to the following questions to usabilityrecruiting@mathworks.com
1. Which of the following best describes your experience with Design of Experiment (DOE)?
a. I regularly use DOE in my work and am comfortable designing experiments and analyzing results
b. I have used DOE in a few projects and understand its principles and applications
c. I have a basic understanding of DOE concepts but have limited practical experience
d. I have never used DOE but I’m interested in learning
-
2. Briefly describe one of your recent projects where you used/want to use DOE. What are the objectives and outcomes?
-
Thank you!
JH
JH
Ultima attività il 28 Apr 2025 alle 20:24

This website is not very attractive or easy to navigate. It is difficult to even find this section - if you start at the Mathworks website, there is no community tab:
You have to go to Help Center, which takes you to documentation, and then click on Community (redirecting you from https://www.mathworks.com/help to https://www.mathworks.com/matlabcentral)
Once you get there it's still a mess
If I have a question, it's not clear whether I should go to MATLAB Answers, Discussions, or Communities. It's not clear what the People page is for, or why it's split off from Community Advisors and Virtual Badges. "Cody" isn't very self-explanatory, and people will only stumble on it by accident, this seems like it should be integrated with contests. Don't get me started on the mess of a Blogs page. My browser knows that I speak English, so why am I being served Japanese language blogs?
I know that web design isn't the main priority of Mathworks, but the website has a very early-2010's look that increasingly feels dated. I hope there will be more consideration given to web UI/UX in the future.
I recently started learning MATLAB and Simulink, and I’m exploring the MathWorks website for study materials. Are there any free tutorials, examples, or beginner guides available directly from their official site? Also, are there special sections for students or personal users to access learning content without needing a full license?
John Kelly
John Kelly
Ultima attività il 24 Apr 2025 alle 3:56

What’s your favorite response from the 'why' command in MATLAB?
T < 2 years
38%
2 years < T < 5 years
26%
5 years < T < 10 years
18%
10 years < T < 20 years
11%
T > 20 years
8%
10172 voti
Los invito a conocer el libro "Sistemas dinámicos en contexto: Modelación matemática, simulación, estimación y control con MATLAB", el cual ya está disponible en formato digital.
El libro integra diversos temas de los sistemas dinámicos desde un punto de vista práctico utilizando programas de MATLAB y simulaciones en Simulink y utilizando métodos numéricos (ver enlace). Existe mucho material en el blog del libro con posibilidades para comentarios, propuestas y correcciones. Resalto los casos de estudio
Creo que el libro les puede dar un buen panorama del área con la posibilidad de experimentar de manera interactiva con todo el material de MATLAB disponible en formato Live Script. Lo mejor es que se pueden formular preguntas en el blog y hacer propuestas al autor de ejercicios resueltos.
Son bienvenidos los comentarios, sugerencias y correcciones al texto.
Steve Eddins
Steve Eddins
Ultima attività il 16 Apr 2025 alle 14:10

In 2019, I wrote a MATLAB Central blog post called "The tool builder's gene (or how to get a job at MathWorks)." In it, I explained my personal theory of a characteristic of some engineers that is key for becoming successful software developers at MathWorks.
I just shared this essay on my personal blog, along with a couple of updates.
Steve Eddins
Steve Eddins
Ultima attività il 15 Apr 2025 alle 21:13

Over the last 5 years or so, the highest-traffic post on my MATLAB Central image processing blog was not actually about image processing; it was about changing the default line thickness in plots.
Now I have written about some other MATLAB plotting behavior that I have recently changed to suit my own preferences. See this new blog post.
Here is a standard MATLAB plot:
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
I don't like some aspects of this plot, and so I have put the following code into my startup file.
set(groot,"DefaultLineLineWidth",2)
set(groot,"DefaultAxesXLimitMethod","padded")
set(groot,"DefaultAxesYLimitMethod","padded")
set(groot,"DefaultAxesZLimitMethod","padded")
set(groot,"DefaultAxesXGrid","on")
set(groot,"DefaultAxesYGrid","on")
set(groot,"DefaultAxesZGrid","on")
With those defaults changed, here is my preferred appearance:
plot(x,y1,x,y2)

Starting in MATLAB R2022a, use the append option in exportgraphics to create GIF files from animated axes, figures, or other visualizations.

This basic template contains just two steps:

% 1. Create the initial image file
gifFile = 'myAnimation.gif';
exportgraphics(obj, gifFile);
% 2. Within a loop, append the gif image
for i = 1:20
      %   %   %   %   %   %    % 
      % Update the figure/axes %
      %   %   %   %   %   %    % 
      exportgraphics(obj, gifFile, Append=true);
  end

Note, exportgraphics will not capture UI components such as buttons and knobs and requires constant axis limits.

To create animations of images or more elaborate graphics, learn how to use imwrite to create animated GIFs .

Share your MATLAB animated GIFs in the comments below!

See Also

This Community Highlight is attached as a live script

clc; clear; close all;
% Initial guess for [x1, x2, x3] (adjust as needed)
x0 = [0.2,0.35,0.5];
% No linear constraints
A = []; b = [];
Aeq = []; beq = [];
% Lower and upper bounds (adjust based on the problem)
lb = [0,0,0];
ub = [pi/2,pi/2,pi/2];
% Optimization options
options = optimoptions('fmincon', 'Algorithm', 'sqp', 'Display', 'iter');
% Solve with fmincon
[x_opt, fval, exitflag] = fmincon(@objective, x0, A, b, Aeq, beq, lb, ub, @nonlinear_constraints, options);
Iter Func-count Fval Feasibility Step Length Norm of First-order step optimality 0 4 4.125000e-01 1.537e+00 1.000e+00 0.000e+00 1.000e+00 1 8 5.464781e-01 9.718e-01 1.000e+00 2.734e-01 1.613e+01 2 12 4.828194e-01 6.526e-02 1.000e+00 9.158e-02 1.518e+01 3 41 4.828194e-01 6.526e-02 3.220e-05 9.264e-07 1.518e+01 Converged to an infeasible point. fmincon stopped because the size of the current step is less than the value of the step size tolerance but constraints are not satisfied to within the value of the constraint tolerance.
% Display results
fprintf('Optimal Solution: x1 = %.4f, x2 = %.4f, x3 = %.4f\n', x_opt(1), x_opt(2), x_opt(3));
Optimal Solution: x1 = 0.1879, x2 = 0.2227, x3 = 0.6308
fprintf('Exit Flag: %d\n', exitflag);
Exit Flag: -2
%% Objective function (minimizing sum of squared errors)
function f = objective(x)
f = sum(x.^2); % Dummy function (since we only want to solve equations)
end
%% Nonlinear constraints (representing the trigonometric equations)
function [c, ceq] = nonlinear_constraints(x)
% Example nonlinear trigonometric equations:
ceq(1) = cos(x(1))+cos(x(2))+cos(x(3))-3*0.9; % First equation
ceq(2) = cos(5*x(1))+cos(5*x(2))+cos(5*x(3)); % Second equation
ceq(3) = cos(7*x(1))+cos(7*x(2))+cos(7*x(3)); % Third equation
c = [x(1)-x(2); x(2)-x(3)]; % No inequality constraints
end
Adam Danz
Adam Danz
Ultima attività il 10 Apr 2025 alle 22:29

I rarely/never save .fig files
47%
Continue working on it later
16%
Archive for future reference
23%
Share within my organization
10%
Share outside my organization
2%
Other (please leave a comment)
2%
2097 voti
I have written, tested, and prepared a function with four subsunctions on my computer for solving one of the problems in the list of Cody problems in MathWorks in three days. Today, when I wanted to upload or copy paste the codes of the function and its subfunctions to the specified place of the problem of Cody page, I do not see a place to upload it, and the ability to copy past the codes. The total of the entire codes and their documentations is about 600 lines, which means that I cannot and it is not worth it to retype all of them in the relevent Cody environment after spending a few days. I would appreciate your guidance on how to enter the prepared codes to the desired environment in Cody.

Informazioni su Discussions

Discussions is a user-focused forum for the conversations that happen outside of any particular product or project.

Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!

Altre aree comunitarie

MATLAB Answers

Poni e rispondi a domande su MATLAB e Simulink

Scambio di file

Scarica o contribuisci al codice inviato da un utente

Cody

Risolvi problemi, impara ad usare MATLAB e ottieni badge

Blog

Scopri MATLAB e Simulink dall’interno

Area giochi di chat AI

Utilizza l'intelligenza artificiale per generare la bozza iniziale del codice MATLAB e rispondere alle domande!