Contenido principal

goc3
goc3
Last activity el 6 de Nov. de 2023

Have you ever learned that something you were doing manually in MATLAB was already possible using a built-in feature? Have you ever written a function only to later realize (or be told) that a built-in function already did what you needed?
Two such moments come to mind for me.
1. Did you realize that you can set conditional breakpoints? Neither did I, until someone showed me that feature. To do that, open or create a file in the editor, right click on a line number for any line that contains code, and select Set Conditional Breakpoint... This will bring up a dialog wherein you can type any logical condition for which execution should be paused. Before I learned about this, I would manually insert if-statements during debugging. Then, after fixing each bug, I would have to delete those statements. This built-in feature is so much better.
2. Have you ever needed to plot horizontal or vertical lines in a plot? For the longest time, I would manually code such lines. Then, I learned about xline() and yline(). Not only is less code required, these lines automatically span the entire axes while zooming, panning, or adjusting axis limits!
Share your own Aha! moments below. This will help everyone learn about MATLAB functionality that may not be obvious or front and center.
(Note: While File Exchange contains many great contributions, the intent of this thread is to focus on built-in MATLAB functionality.)

Four (of many) new features for Apps in MATLAB R2021a

These four new features are the solutions to many inquiries in the Answers forum that continue to receive hundreds of views per month long after they were asked.

Table of Contents

  • Keyboard Shortcuts for UI Components
  • Programmatically scroll UITables
  • Figure always on top
  • UI hyperlink component
  • Demo app: Keyboard shortcut challenge

Keyboard Shortcuts for UI Components

Keyboard shortcuts can now change the focus and make contiguous and non-contiguous selections in ListBox, Table, DatePicker, and ColorPicker menus created in uifigures. The table below summarizes the shortcuts made available in R2021a ( release notes ).

Reminder: in MATLAB R2020b and later you can change the tab order of objects in an app by changing their stack order in AppDesigner using the Reorder tool in the drop-down menu or by right-clicking the component and selecting Reorder from the menu (see R2020b release notes and a screenshot in the Answers forum ).

Programmatically scroll UITables

The scroll function was added in R2016a but as of R2021a it can be used with uitables to programmatically scroll to the top, bottom, left, or right of a table or to a specific row, column or cell ( release notes ). Combined with a uistyle (R2019b) you can scroll to and highlight any part of the uitable.

Syntax examples:

Figure always on top

Figures created with uifigure now have an additional WindowStyle property: 'alwaysontop' ( release notes ). Figures with this setting will stay on top of other windows but unlike the modal option, other windows are still accessible.

See the WindowStyle property description for tips on setting and changing this property.

To toggle the AlwaysOnTop state of your app using a checkbox, state button, or another UI component, follow this callback function template,

function alwaysOnTopCheckBoxValueChanged(app, event)
    value = app.alwaysOnTopCheckBox.Value;
    if value
        app.UIFigure.WindowStyle = 'alwaysontop';
    else
        app.UIFigure.WindowStyle = 'normal';
    end
end

UI hyperlink component

Use the uihyperlink function or the UI hyperlink component in App Designer or a uifigure to add and configure a clickable link ( release notes ). The hyperlink can be assigned to a figure, panel object, tab object, ButtonGroup, or GridLayout object when created in a uifigure. In addition to setting the text and URL, there are lots of properties to control the text format including the VisitedColor property that controls the color of the text after the link is clicked and an optional user-defined HyperlinkClickedFcn function that is evoked when the link is clicked.

Demo app: Keyboard shortcut challenge

The attached zip file contains an app, keyboardShortcutsDemo_R2021a.mlapp , that demonstrates these 4 features. The app displays the extent of arctic sea ice from 1979 to 2016 during the months when extent typically maximizes and minimizes.

Mouseless challenge: After opening the app, without using your mouse, try the following.

  • Select a month (September or March) and any number of years from the list boxes
  • Navigate through the Date Picker and select a date within the range or your selected years (disabled when only 1 year is selected).
  • Navigate to the always-on-top checkbox to pin the app to the top of other windows.
  • Navigate to the text box and enter a year that appears in the uitable to go to that row in the uitable (disabled when only 1 year is selected).
  • Navigate to the URL and press Enter to open the website containing the raw data.

Download the attached zip file, FourNewAppFeatures_R2021a.zip, for a Live script copy of this thread and an app that demonstrates each feature.

  1. Use the new exportapp function to capture an image of your app|uifigure
  2. MATLAB's getframe now supports apps & uifigures
  3. Review: How to get the handle to an app figure

Use the new exportapp function to capture an image of your app|uifigure

Imagine these scenarios:

  • Your app contains several adjustable parameters that update an embedded plot and you'd like to remember the values of each app component so that you can recreate the plot with the same dataset
  • You're constructing a manual for your app and would like to include images of your app
  • You're app contains a process that automatically updates regularly and you'd like to store periodic snapshots of your app.

As of MATLABs R2020b release , we no longer must rely on 3rd party software to record an image of an app or uifigure.

exportapp(fig,filename) saves an image (JPEG | PNG | TIFF | PDF) of a uifigure ( fig) with the specified file name or full file path ( filename). MATLAB's documentation includes an example of how to add an [Export] button to an app that allows the user to select a path, filename, and extension for their exported image.

Here's another example that merely saves the image as a PDF to the app's main folder.

1. Add a button to the app and assign a ButtonPushed callback function to the button. This one also assigns an icon to the button in the form of an svg file.

2. Define the callback function to name the image after the app's name and include a datetime stamp. The image will be saved to the app's main folder.

% Button pushed function: SnapshotButton
function SnapshotButtonPushed(app, ~) 
    % create filename containing the app's figure name (spaces removed)
    % and a datetime stamp in format yymmdd_hhmmss
    filename = sprintf('%s_%s.pdf',regexprep(app.MyApp.Name,' +',''), datestr(now(),'yymmdd_HHMMSS'));
    % Get the app's path
    filepath = fileparts(which([mfilename,'.mlapp']));
    % Store snapshot
    exportapp(app.MyApp, fullfile(filepath,filename))
end

Matlab's getframe now supports apps & uifigures

getframe(h) captures images of axes or a uifigure as a structure containing the image data which defines a movie frame. This function has been around for a while but as of r2020b , it now supports uifigures. By capturing consecutive frames, you can create a movie that can be played back within a Matlab figure (using movie ) or as an AVI file (using VideoWriter ). This is useful when demonstrating the effects of changes to app components.

The general steps to recording a process within an app as a movie are,

1. Add a button or some other event to your app that can invoke the frame recording process.

2. Animation is typically controlled by a loop with n iterations. Preallocate the structure array that will store the outputs to getframe. The example below stores the outputs within the app so that they are available by other functions within the app. That will require you to define the variable as a property in the app.

% nFrames is the number of iterations that will be recorded.
% recordedFrames is defined as a private property within the app
app.recordedFrames(1:nFrames) = struct('cdata',[],'colormap',[]);

3. Call getframe from within the loop that controls the animation. If you're using VideoWriter to create an AVI file, you'll also do that here (not shown, but see an example in the documentation ).

% app.myAppUIFigure: the app's figure handle
% getframe() also accepts axis handles
for i = 1:nFrames
      ... % code that updates the app for the next frame
      app.recordedFrames(i) = getframe(app.myAppUIFigure);
  end

4. Now the frame data are stored in app.recordedFrames and can be accessed from anywhere within the app. To play them back as a movie,

movie(app.recordedFrames) 
% or 
movie(app.recordedFrames, n) % to play the movie n-times
movie(app.recordedFrames, n, fps) % to specify the number of frames per second

To demonstrate this, I adapted a copy of Matlab's built-in PulseGenerator.mlapp by adding

  • a record button
  • a record status lamp with frame counter
  • a playback button
  • a function that animates the effects of the Edge Knob

Recording process (The GIF is a lot faster than realtime and only shows part of the recording) (Open the image in a new window or see the attached Live Script for a clearer image).

Playback process (Open the image in a new window or see the attached Live Script for a clearer image.)

Review: How to get the handle to an app figure

To use either of these functions outside of app designer, you'll need to access the App's figure handle. By default, the HandleVisibility property of uifigures is set to off preventing the use of gcf to retrieve the figure handle. Here are 4 ways to access the app's figure handle from outside of the app.

1. Store the app's handle when opening the app.

app = myApp;
% Get the figure handle
figureHandle = app.myAppUIFigure;

2. Search for the figure handle using the app's name, tag, or any other unique property value

allfigs = findall(0, 'Type', 'figure'); % handle to all existing figures
figureHandle = findall(allfigs, 'Name', 'MyApp', 'Tag', 'MyUniqueTagName');

3. Change the HandleVisibility property to on or callback so that the figure handle is accessible by gcf anywhere or from within callback functions. This can be changed programmatically or from within the app designer component browser. Note, this is not recommended since any function that uses gcf such as axes(), clf(), etc can now access your app!.

4. If the app's figure handle is needed within a callback function external to the app, you could pass the app's figure handle in as an input variable or you could use gcbf() even if the HandleVisibility is off.

See a complete list of changes to the PulseGenerator app in the attached Live Script file to recreate the app.