Your Search Bar For Shrewd Tips

How To Close Uifigure Matlab


Knowing how to close a uifigure in MATLAB is useful when you are building interactive apps, writing scripts that open temporary windows, or adding a reliable exit button. In most cases, the simplest command is close(fig), where fig is the handle returned by uifigure. However, the best approach depends on whether you want to run a close callback, delete the window immediately, close several windows, or give users a chance to confirm their choice. This guide explains each method and shows how to close a MATLAB UI figure safely.

The Quickest Way to Close a UIFigure in MATLAB

When you create a UI figure, save its handle in a variable. You can then pass that handle to MATLAB’s close function whenever the window should close.

fig = uifigure('Name', 'My App');

% Close the UI figure later
close(fig);

The handle identifies the specific window to close. This is safer than closing every open figure, especially in a script or app that may run alongside other MATLAB windows. You can call close(fig) from a button callback, another function, or the MATLAB Command Window, as long as fig is still available.

If the figure has no custom close-request behavior, MATLAB closes it. If it has a CloseRequestFcn, MATLAB runs that callback when the close request is made. This makes close(fig) a good default when your app needs to perform cleanup or ask the user a question before closing.

Close a UIFigure from a Button Callback

A common requirement is to add a button that closes the current UI figure. Create a button inside the figure and assign a callback. In the callback, use the figure handle directly or use the callback’s source figure.

fig = uifigure('Name', 'Example');

btn = uibutton(fig, ...
    'Text', 'Close', ...
    'Position', [20 20 100 30], ...
    'ButtonPushedFcn', @(btn, event) close(fig));

For reusable code, it is often better to avoid relying on a variable from the surrounding workspace. A nested callback can access the figure handle, while a callback function can receive the figure as an input. For example, the button’s parent is the UI figure, so the callback can close that parent:

fig = uifigure('Name', 'Example');

btn = uibutton(fig, ...
    'Text', 'Close', ...
    'Position', [20 20 100 30], ...
    'ButtonPushedFcn', @(btn, event) close(btn.Parent));

This pattern works when the button is a direct child of the figure. If your button is inside a panel or another container, btn.Parent refers to that container rather than the figure. In that case, keep and use the figure handle, or navigate from the button to the appropriate parent object.

Understand the Difference Between close and delete

MATLAB provides both close and delete for removing a UI figure, but they are not interchangeable in every situation.

  • close(fig) requests that the figure close. If a close-request callback is defined, MATLAB runs it. The callback can perform cleanup, display a confirmation dialog, or decide not to close the window.
  • delete(fig) deletes the figure handle directly. It does not follow the normal close-request process, so a custom CloseRequestFcn is not used to manage the deletion.

Use close(fig) when you want to respect the window’s normal closing behavior. Use delete(fig) when your code intentionally needs to remove the figure immediately and you have already handled any required cleanup. Direct deletion is useful in controlled situations, but it can skip logic that users or your app rely on.

For instance, if a figure contains unsaved data, calling delete(fig) may remove the window without first asking whether the user wants to save. In an interactive app, build the confirmation or save workflow into the close callback, then use close(fig) to start that workflow.

Use CloseRequestFcn to Control How a UIFigure Closes

The CloseRequestFcn property lets you decide what happens when a user clicks the window’s close button or your code requests closure with close(fig). A close-request callback must eventually delete the figure if the app is meant to close. Calling close(src) from inside the callback can trigger the same callback again, so use delete(src) after completing your custom logic.

fig = uifigure('Name', 'Custom Close');

fig.CloseRequestFcn = @(src, event) delete(src);

For more involved behavior, use a named callback function. The following example displays a confirmation dialog before deleting the figure:

fig = uifigure('Name', 'Confirm Before Closing');
fig.CloseRequestFcn = @confirmClose;

function confirmClose(src, ~)
    choice = uiconfirm(src, ...
        'Do you want to close this window?', ...
        'Confirm Close', ...
        'Options', {'Close', 'Cancel'}, ...
        'DefaultOption', 2, ...
        'CancelOption', 2);

    if strcmp(choice, 'Close')
        delete(src);
    end
end

When the user chooses Close, the callback deletes the figure. When they choose Cancel or dismiss the dialog, the figure remains open. Keep the confirmation logic in the close-request callback if you want it to apply consistently to the title-bar close button and calls to close(fig).

In scripts, local functions must be placed after the script’s executable statements, and MATLAB release requirements can vary. If your code does not support local functions in scripts, put the callback in a separate function file or define it as a nested function inside a function file.

Close a UIFigure in App Designer

In App Designer, the UI figure belongs to the app object. If you want to close an app from one of its callbacks, use the app’s figure handle and follow the app’s lifecycle pattern. A common close-request callback deletes the app object:

function UIFigureCloseRequest(app, event)
    delete(app);
end

Deleting the app object allows its cleanup code to run and removes the app’s UI. This is generally preferable to deleting only app.UIFigure, because an App Designer app may also own timers, listeners, data objects, or other resources that should be cleaned up together.

For a button inside an App Designer app, you can close the app using the same lifecycle approach:

function CloseButtonPushed(app, event)
    delete(app);
end

If the app needs to confirm before closing, put the confirmation logic in the figure’s close-request callback. When the user approves, delete the app object. If the user cancels, leave the app running. Avoid adding multiple unrelated closing paths that could leave app resources active after the window disappears.

Close Multiple UIFigures

To close every open figure, including UI figures in workflows where MATLAB recognizes them as figures, you can use:

close all

This is convenient for cleanup at the end of a standalone script or during development. It is also broad: it can close figures that belong to other work, so avoid using it in shared sessions or apps unless closing all open figures is genuinely intended.

When you need to close a specific set of figure handles, keep those handles and close them individually. You can also find figure objects and iterate over them:

figures = findall(groot, 'Type', 'figure');

for k = 1:numel(figures)
    close(figures(k));
end

This approach sends a close request to each figure, allowing its close-request callback to run. Because callbacks may cancel closing or modify the set of open figures, test this pattern with your app’s behavior. If only one particular UI figure should close, use its handle rather than searching for every figure.

Check Whether a UIFigure Is Still Open

Code may try to close a figure that has already been removed, especially when callbacks, timers, or asynchronous operations are involved. Before closing a saved handle, check that it is still valid:

if isvalid(fig)
    close(fig);
end

Validity checks are most useful in longer-running apps where more than one part of the program can close the same window. Keep in mind that the handle variable must exist before you can test it. A simple pattern is to initialize the variable when creating the figure and clear or update it as part of your app’s cleanup.

Common UIFigure Closing Problems and Fixes

  • The window does not close: Check whether CloseRequestFcn is defined. A callback that does not eventually delete the figure will leave it open. Add the intended close action after any checks or prompts.
  • The callback runs repeatedly: Avoid calling close(src) from inside the close-request callback. That can trigger the callback again. Use delete(src) after the callback has decided to close.
  • The wrong object closes: Confirm that the variable passed to close is the figure handle, not a button, panel, or other component. A component’s Parent may be a container rather than the figure.
  • Other windows close unexpectedly: Replace close all with close(fig) or a loop over only the handles your code owns.
  • App resources remain active: In App Designer, close the app through its app object and ensure cleanup code handles timers, listeners, and other resources.

When debugging, temporarily add a message or breakpoint inside the close-request callback. This helps you verify whether MATLAB is invoking the callback and whether the code reaches the point where the figure or app is deleted.

Best Practices for Closing a UIFigure

For reliable MATLAB UI figure management, keep a reference to each figure you create and close only the intended handle. Prefer close(fig) for normal user-driven closing because it respects close-request behavior. Use delete(fig) inside a close-request callback only after the app has decided to proceed. In App Designer, delete the app object when you want to shut down the whole app, rather than removing only its visible window.

Also make closing behavior consistent. If a title-bar close button asks users to confirm but an in-app button immediately deletes the window, users may be surprised. Route both actions through the same confirmation or cleanup logic. Finally, test the close behavior with unsaved data, repeated close requests, and any background tasks your app uses.

Conclusion

The standard way to close a MATLAB uifigure is close(fig), using the handle returned when the figure is created. Choose delete(fig) only when you intentionally want to remove the figure directly, and use CloseRequestFcn to manage confirmation or cleanup before a window closes. For App Designer, shut down the app through its app object. By targeting the correct handle and using a consistent closing workflow, you can close UI figures safely without disrupting other MATLAB windows or leaving app resources behind.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →