Results for
Starting in MATLAB R2021a, name-value arguments have a new optional syntax!
A property name can be paired with its value by an equal sign and the property name is not enclosed in quotes.
Compare the comma-separated name,value syntax to the new equal-sign syntax, either of which can be used in >=r2021a:
- plot(x, y, "b-", "LineWidth", 2)
- plot(x, y, "b-", LineWidth=2)
It comes with some limitations:
- It's recommended to use only one syntax in a function call but if you're feeling rebellious and want to mix the syntaxes, all of the name=value arguments must appear after the comma-separated name,value arguments.
- Like the comma-separated name,value arguments, the name=value arguments must appear after positional arguments.
- Name=value pairs must be used directly in function calls and cannot be wrapped in cell arrays or additional parentheses.
Some other notes:
- The property names are not case-sensitive so color='r' and Color='r' are both supported.
- Partial name matches are also supported. plot(1:5, LineW=4)
The new syntax is helpful in distinguishing property names from property values in long lists of name-value arguments within the same line.
For example, compare the following 2 lines:
h = uicontrol(hfig, "Style", "checkbox", "String", "Long", "Units", "Normalize", "Tag", "chkBox1")
h = uicontrol(hfig, Style="checkbox", String="Long", Units="Normalize", Tag="chkBox1")
Here's another side-by-side comparison of the two syntaxes. See the attached mlx file for the full code and all content of this Community Highlight.
tiledlayout, introduced in MATLAB R2019b, offers a flexible way to add subplots, or tiles, to a figure.
Reviewing two changes to tiledlayout in MATLAB R2021a
- The new TileIndexing property
- Changes to TileSpacing and Padding properties
1) TileIndexing
By default, axes within a tiled layout are created from left to right, top to bottom, but sometimes it's better to organize plots column-wise from top to bottom and then left to right. Starting in r2021a, the TileIndexing property of tiledlayout specifies the direction of flow when adding new tiles.
tiledlayout(__,'TileIndexing','rowmajor') creates tiles by row (default).
tiledlayout(__,'TileIndexing','columnmajor') creates tiles by column.
.
2) TileSpacing & Padding changes
Some changes have been made to the spacing properties of tiles created by tiledlayout.
TileSpacing: sets the spacing between tiles.
- "loose" is the new default and replaces "normal" which is no longer recommended but is still accepted.
- "tight" replaces "none" and brings the tiles closer together still leaving space for axis ticks and labels.
- "none" results in tile borders touching, following the true meaning of none.
- "compact" is unchanged and has slightly more space between tiles than "tight".
Padding: sets the spacing of the figure margins.
- "loose" is the new default and replaces "normal" which is no longer recommended but is still accepted.
- "tight" replaces "none" and reduces the figure margins. "none" is no longer recommended but is still accepted.
- "compact" is unchanged and adds slightly more marginal space than "tight".
- Reducing the figure margins to a true none is still not an option.
The release notes show a comparison of these properties between r2020b and r2021a.
Here's what the new TileSpacing options (left column of figures below) and Padding options (right column) look like in R2021a. Spacing properties are written in the figure names.
.
And here's a grid of all 12 combinations of the 4 TileSpacing options and 3 Padding options in R2021a.
.
Code used to generate these figures
%% Animate the RowMajor and ColumnMajor indexing with colored tiles fig1 = figure('position',[200 200 560 420]); tlo1 = tiledlayout(fig1, 3, 3, 'TileIndexing','rowmajor'); title(tlo1, 'RowMajor indexing')
fig2 = figure('position',[760 200 560 420]); tlo2 = tiledlayout(fig2, 3, 3, 'TileIndexing','columnmajor'); title(tlo2, 'ColumnMajor indexing')
colors = jet(9); drawnow()
for i = 1:9 ax = nexttile(tlo1); ax.Color = colors(i,:); text(ax, .5, .5, num2str(i), 'Horiz','Cent','Vert','Mid','Fontsize',24)
ax = nexttile(tlo2); ax.Color = colors(i,:); text(ax, .5, .5, num2str(i), 'Horiz','Cent','Vert','Mid','Fontsize',24)
drawnow pause(.3) end
%% Show TileSpacing options tileSpacing = ["loose","compact","tight","none"]; figHeight = 140; % unit: pixels figPosY = fliplr(50 : figHeight+32 : (figHeight+30)*numel(tileSpacing));
for i = 1:numel(tileSpacing) uif = uifigure('Units','Pixels','Position', [150 figPosY(i) 580 figHeight], ... 'Name', ['TileSpacing: ', tileSpacing{i}]); tlo = tiledlayout(uif,1,3,'TileSpacing',tileSpacing(i)); h = arrayfun(@(i)nexttile(tlo), 1:tlo.GridSize(2)); box(h,'on') drawnow() end
%% Show Padding options padding = ["loose","compact","tight"]; for i = 1:numel(padding) uif = uifigure('Units','Pixels','Position', [732 figPosY(i) 580 figHeight], ... 'Name', ['Padding: ', padding{i}]); tlo = tiledlayout(uif,1,3,'Padding',padding(i)); h = arrayfun(@(i)nexttile(tlo), 1:tlo.GridSize(2)); box(h,'on') drawnow() end
%% Show all combinations of TileSpacing and Padding options tileSpacing = ["loose","compact","tight","none"]; padding = ["loose","compact","tight"]; [tsIdx, padIdx] = meshgrid(1:numel(tileSpacing), 1:numel(padding)); figSize = [320 220]; % width, height (pixels) figPosX = 150 + (figSize(1)+2)*(0:numel(tileSpacing)-1); figPosY = 50 + (figSize(2)+32)*(0:numel(padding)-1); [figX, figY] = meshgrid(figPosX, fliplr(figPosY)); for i = 1:numel(padIdx) uif = uifigure('Units','pixels','Position',[figX(i), figY(i), figSize], ... 'name', ['TS: ', tileSpacing{tsIdx(i)}, ', Pad: ', padding{padIdx(i)}]); tlo = tiledlayout(uif,2,2,'TileSpacing',tileSpacing(tsIdx(i)),'Padding',padding(padIdx(i))); h = arrayfun(@(i)nexttile(tlo), 1:prod(tlo.GridSize)); box(h,'on') drawnow() end
Did you know you can use most emoticons in text objects?
Most emoticons are just unicode characters. Using them as characters in Matlab is as simple as finding their numeric representation and then converting the numeric value back to character. Not all emoticons are convertible in Matlab.
Here's a secret message with emoticons. Use char(x) to decode it.
x = [79 77 71 33 32 55357 56878 32 104 97 118 101 32 121 111 ... 117 32 117 112 100 97 116 101 100 32 116 111 32 77 97 116 ... 108 97 98 32 55358 56595 32 114 50 48 50 49 97 32 121 101 116 32 8265];
Happy St. Patrick's Day!
fig = figure('MenuBar','none','Color', [0 .62 .376]); % Shamrock green ax = axes(fig,'Units','Normalized','Position',[0 0 1 1]); axis(ax,'off') axis(ax,'equal') hold(ax,'on') xlim(ax,[-1,1]); ylim(ax,[-1,1]) text(ax, 0, 0, char(9752), 'VerticalAlignment','middle','HorizontalAlignment','center','FontSize', 200) str = num2cell('Happy St Patrick''s day!'); th = linspace(-pi/2,pi/2,numel(str)); txtHandle = text(ax,sin(th)*.8, cos(th)*.8, str, 'VerticalAlignment','middle','HorizontalAlignment','center','FontSize', 25); set(txtHandle,{'rotation'}, num2cell(rad2deg(-th'))) thr = 0.017; rotateCCW = @(xyz)([cos(thr) -sin(thr) 0; sin(thr), cos(thr), 0; 0 0 1]*xyz.').'; while all(isvalid(txtHandle)) newposition = rotateCCW(vertcat(txtHandle.Position)); set(txtHandle,{'position'}, mat2cell(newposition,ones(numel(txtHandle),1),3), ... {'rotation'}, num2cell([txtHandle.Rotation].'+thr*180/pi)) drawnow() end
We've all been there. You've got some kind of output that displays perfectly in the command window and you just want to capture that display as a string so you can use it again somewhere else. Maybe it's a multidimensional array, a table, a structure, or a fit object that perfectly displays the information you need in a neat and tidy format but when you try to recreate the display in a string variable it's like reconstructing the Taj Mahal out of legos.
Enter Matlab r2021a > formattedDisplayText()
Use str=formattedDisplayText(var) the same way you use disp(var) except instead of displaying the output, it's stored as a string as it would appear in the command window.
Additional name-value pairs allow you to
- Specify a numeric format
- Specify loose|compact line spacing
- Display true|false instead of 1|0 for logical values
- Include or suppress markup formatting that may appear in the display such as the bold headers in tables.
Demo: Record the input table and results of a polynomial curve fit
load census [fitobj, gof] = fit(cdate, pop, 'poly3', 'normalize', 'on')
Results printed to the command window:
fitobj = Linear model Poly3: fitobj(x) = p1*x^3 + p2*x^2 + p3*x + p4 where x is normalized by mean 1890 and std 62.05 Coefficients (with 95% confidence bounds): p1 = 0.921 (-0.9743, 2.816) p2 = 25.18 (23.57, 26.79) p3 = 73.86 (70.33, 77.39) p4 = 61.74 (59.69, 63.8)
gof = struct with fields:
sse: 149.77 rsquare: 0.99879 dfe: 17 adjrsquare: 0.99857 rmse: 2.9682
Capture the input table, the printed fit object, and goodness-of-fit structure as strings:
rawDataStr = formattedDisplayText(table(cdate,pop),'SuppressMarkup',true) fitStr = formattedDisplayText(fitobj) gofStr = formattedDisplayText(gof)
Display the strings:
rawDataStr = " cdate pop _____ _____ 1790 3.9 1800 5.3 1810 7.2 1820 9.6 1830 12.9 1840 17.1 1850 23.1 1860 31.4 1870 38.6 1880 50.2 1890 62.9 1900 76 1910 92 1920 105.7 1930 122.8 1940 131.7 1950 150.7 1960 179 1970 205 1980 226.5 1990 248.7 "
fitStr = " Linear model Poly3: ary(x) = p1*x^3 + p2*x^2 + p3*x + p4 where x is normalized by mean 1890 and std 62.05 Coefficients (with 95% confidence bounds): p1 = 0.921 (-0.9743, 2.816) p2 = 25.18 (23.57, 26.79) p3 = 73.86 (70.33, 77.39) p4 = 61.74 (59.69, 63.8) "
gofStr = " sse: 149.77 rsquare: 0.99879 dfe: 17 adjrsquare: 0.99857 rmse: 2.9682 "
Combine the strings into a single string and write it to a text file in your temp directory:
txt = strjoin([rawDataStr; fitStr; gofStr],[newline newline]); file = fullfile(tempdir,'results.txt'); fid = fopen(file,'w+'); cleanup = onCleanup(@()fclose(fid)); fprintf(fid, '%s', txt); clear cleanup
Open results.txt.
winopen(file) % for Windows platforms
MATLAB Answers will now properly handle the use of the '*@*' character when you want to get someone's attention. This behavior is commonly referred to as 'mentioning' or 'tagging' someone and is a feature found in most communication apps.
Why we are doing this
To help with communication and potentially speed up conversations. Also, it turns out many of you have been typing the @ character in Answers already, even though the MATLAB Answers site didn't behave in the expected way.
How it works
Once you type the @ character a popup will appear listing the community members already in the Q/A thread, as you keep typing the list will expand to include members not in the thread. A mentioned user will receive a notification when the question/answer/comment is posted. Each mention in the Q/A thread will have a new visual style and link to the user profile for that community member.
If you don't want to get 'mentioned' you can turn off the setting in your communication preferences located on your profile page .
We hope you will find this feature helpful and as always please reply with any feedback you may have.
We have created a new community for users of ThingSpeak. This new community is for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.
Christopher Stapels will be moderating the new ThingSpeak community .
We encourage you to visit the new community and share best practices, examples, and ask questions.
Ameer Hamza had a great 2020 and has been awarded the coveted MOST ACCEPTED answers badge for all his contributions in MATLAB Answers this past year. Ameer joins Walter Roberson and Image Analyst in receiving this award going all the way back to 2012!
There are 10 community members who have achieved the Top Downloads badge for their popular File Exchange submissions in 2020. Do you recognize any of these names? There's a good chance you've used one or more of their toolboxes or scripts in your work if you're a frequent visitor to File Exchange, if you're not you might want to check out what they've posted, it may save you a lot of time writing your own code.
--------------------- Top Downloads Badge Winners -----------------
- PIRC
- Scott Lowe
- Yair Altman
- Dr. Siva Malla
- Chad Greene
- Seyedali Mirjalili
- Giampiero Campa
- Rodney Tan
- John D'Errico
- Steve Miller
Congratulations to all these winners and a giant THANK YOU for all they've done this past year to help everyone in the MATLAB Central community!
![](/matlabcentral/discussions/uploaded_files/2223/commHighlighIconSmall.png)
- Use the new exportapp function to capture an image of your app|uifigure
- MATLAB's getframe now supports apps & uifigures
- 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.
![](/matlabcentral/discussions/uploaded_files/2228/SnapshotButton.png)
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).
![](/matlabcentral/discussions/uploaded_files/2243/getFrameInApp_demo_witBar.gif)
Playback process (Open the image in a new window or see the attached Live Script for a clearer image.)
![](/matlabcentral/discussions/uploaded_files/2238/getFrameInApp_playback_withBar.gif)
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.
File Exchange now offers the ability to download/restore previous versions of community contributed files. It's often a good practice to always update your software to the latest version, however there are times when this isn't always helpful. Sometimes a software update can break or alter something you've been relying on, in these cases you'll want to stick with the version that's working for you. This is why we've added the ability to download previous versions in File Exchange.
Using Version History
Navigate to any community member file and then click the View Version History link that appears above the Download button. This will show you a list of the previous versions contributed by the submission author. Each version will have a corresponding download button, date, version number, and a description of the changes made for that update.
![](/matlabcentral/discussions/uploaded_files/2208/Screenshot%202020-10-15%20091637.png)
Let us know what you think about this new feature by replying below.
![](/matlabcentral/discussions/uploaded_files/2166/2020b_heightwidth_img.png)
Prior to r2020b the height (number of rows) and width (number of columns) of an array or table can be determined by the size function,
array = rand(102, 16);
% Method 1 [dimensions] = size(array); h = dimensions(1); w = dimensions(2);
% Method 2 [h, w] = size(array); %#ok<*ASGLU> % or [h, ~] = size(array); [~, w] = size(array);
% Method 3 h = size(array,1); w = size(array,2);
In r2013b, the height(T) and width(T) functions were introduced to return the size of single dimensions for tables and timetables.
Starting in r2020b, height() and width() can be applied to arrays as an alternative to the size() function.
Continuing from the section above,
h = height(array) % h = 102
w = width(array) % w = 16
height() and width() can also be applied to multidimensional arrays including cell and structure arrays
mdarray = rand(4,3,20); h = height(mdarray) % h = 4
w = width(mdarray) % w = 3
The expanded support of the height() and width() functions means,
- when reading code, you can no longer assume the variable T in height(T) or width(T) refers to a table or timetable
- greater flexibility in expressions such as the these, below
% C is a 1x4 cell array containing 4 matrices with different dimensions rng('default') C = {rand(5,2), rand(2,3), rand(3,4), rand(1,1)}; celldisp(C)
% C{1} = % 0.81472 0.09754 % 0.90579 0.2785 % 0.12699 0.54688 % 0.91338 0.95751 % 0.63236 0.96489 % C{2} = % 0.15761 0.95717 0.80028 % 0.97059 0.48538 0.14189 % C{3} = % 0.42176 0.95949 0.84913 0.75774 % 0.91574 0.65574 0.93399 0.74313 % 0.79221 0.035712 0.67874 0.39223 % C{4} = % 0.65548
What's the max number of rows in C?
maxRows1 = max(cellfun(@height,C)) % using height() % maxRows1 = 5;
maxRows2 = max(cellfun(@(x)size(x,1),C)) % using size() % maxRows2 = 5;
What's the total number of columns in C?
totCols1 = sum(cellfun(@width,C)) % using width() %totCols1 = 10
totCols2 = sum(cellfun(@(x)size(x,2),C)) % using size(x,2) % totCols2 = 10
Attached is a live script containing the content of this post.
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/29191/image.png)
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/29196/image.png)
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/29201/image.png)
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/29206/image.png)
Please join Loren Shure for her live sessions on the MATLAB YouTube channel starting October 1st and continuing through November 19th. You know Loren from her popular blog Loren on the Art of MATLAB.
Solve coding problems. Improve MATLAB skills. Have fun. See details and register .
![](/matlabcentral/discussions/uploaded_files/1744/mainImg.png)
Add a subtitle
Multi-lined titles have been supported for a long time but starting in r2020b, you can add a subtitle with its own independent properties to a plot in two easy ways.
- Use the new subtitle function: s=subtitle('mySubtitle')
- Use the new second argument to the title function: [t,s]=title('myTitle','mySubtitle')
![](/matlabcentral/discussions/uploaded_files/1732/subtitl.png)
figure() tiledlayout(2,2)
% Method 1 ax(1) = nexttile; th(1) = title('Pupil size'); sh(1) = subtitle('Happy faces');
ax(2) = nexttile; th(2) = title('Pupil size'); sh(2) = subtitle('Sad faces');
% Method 2 ax(3) = nexttile; [th(3), sh(3)] = title('Fixation duration', 'Happy faces');
ax(4) = nexttile; [th(4), sh(4)] = title('Fixation duration', 'Sad faces');
set(ax, 'xticklabel', [], 'yticklabel', [],'xlim',[0,1],'ylim',[0,1])
% Set all title colors to orange and subtitles colors to purple. set(th, 'Color', [0.84314, 0.53333, 0.1451]) set(sh, 'Color', [0, 0.27843, 0.56078])
Control title/Label alignment
Title and axis label positions can be changed via their Position, VerticalAlignment and HorizontalAlignment properties but this is usually clumsy and leads to other problems when trying to align the title or labels with an axis edge. For example, when the position units are set to 'data' and the axis limits change, the corresponding axis label will change position relative to the axis edges. If units are normalized and the axis position or size changes, the corresponding label will no longer maintain its relative position to the axis, and that's assuming the normalized position was computed correctly in the first place.
Starting in r2020b, title and axis label alignment can be set to center|left|right, relative to the axis edges.
- TitleHorizontalAlignment is a property of the axis: h.TitleHorizontalAlignment='left';
- LabelHorizontalAlignment is a property of the ruler object that defines the x | y | z axis: h.XAxis.LabelHorizontalAlignment='left';
![](/matlabcentral/discussions/uploaded_files/1741/label.png)
% Create data x = randi(50,1,100)'; y = x.*[.2, -.2] + (rand(numel(x),2)-.5)*10; gray = [.65 .65 .65];
% Plot comparison between columns of y figure() tiledlayout(2,2,'TileSpacing','none') ax(1) = nexttile(1); plot(x, y(:,1), 'o', 'color', gray) lsline ylabel('Y1 (units)') title('Regression','Y1 & Y2 separately')
ax(2) = nexttile(3); plot(x, y(:,2), 'd', 'color', gray) lsline xlabel('X Label (units)') ylabel('Y2 (units)') grid(ax, 'on') linkaxes(ax, 'x')
% Move title and labels leftward set(ax, 'TitleHorizontalAlignment', 'left') set([ax.XAxis], 'LabelHorizontalAlignment', 'left') set([ax.YAxis], 'LabelHorizontalAlignment', 'left')
% Combine the two comparisons into plot and flip the second % y-axis so trend are in the same direction ax(3) = nexttile([2,1]); yyaxis('left') plot(x, y(:,1), 'o') ylim([-6,16]) lsline xlabel('X Label (units)') ylabel('Y1 (units) \rightarrow')
yyaxis('right') plot(x, y(:,2), 'd') ylim([-16,6]) lsline ylabel('\leftarrow Y2 (units)') title('Direct comparison','(Y2 axis flipped)') set(ax(3), 'YDir','Reverse')
% Align the ylabels with the minimum axis limit to emphasize the % directions of each axis. Keep the title and xlabel centered ax(3).YAxis(1).LabelHorizontalAlignment = 'left'; ax(3).YAxis(2).LabelHorizontalAlignment = 'right'; ax(3).TitleHorizontalAlignment = 'Center'; % not needed; default value. ax(3).XAxis.LabelHorizontalAlignment = 'Center'; % not needed; default value.
![](/matlabcentral/discussions/uploaded_files/1606/pointers.bmp)
Starting in r2020a , you can change the mouse pointer symbol in apps and uifigures.
The Pointer property of a figure defines the cursor’s default pointer symbol within the figure. You can also create your own pointer symbols (see part 3, below).
![](/matlabcentral/discussions/uploaded_files/1087/allPointers.png)
Part 1. How to define a default pointer symbol for a uifigure or app
For figures or uifigures, set the pointer property when you define the figure or change the pointer property using the figure handle.
% Set pointer when creating the figure uifig = uifigure('Pointer', 'crosshair');
% Change pointer after creating the figure uifig.Pointer = 'crosshair';
For apps made in AppDesigner, you can either set the pointer from the Design View or you can set the pointer property of the app’s UIFigure from the startup function using the second syntax shown above.
![](/matlabcentral/discussions/uploaded_files/1093/appDesignerPointerSettings.png)
Part 2. How to change the pointer symbol dynamically
The pointer can be changed by setting specific conditions that trigger a change in the pointer symbol.
For example, the pointer can be temporarily changed to a busy-symbol when a button is pressed. This ButtonPushed callback function changes the pointer for 1 second.
function WaitasecondButtonPushed(app, event) % Change pointer for 1 second. set(app.UIFigure, 'Pointer','watch') pause(1) % Change back to default. set(app.UIFigure, 'Pointer','arrow') app.WaitasecondButton.Value = false; end
The pointer can be changed every time it enters or leaves a uiaxes or any plotted object within the uiaxes. This is controlled by a set of pointer management functions that can be set in the app’s startup function.
iptSetPointerBehavior(obj,pointerBehavior) allows you to define what happens when the pointer enters, leaves, or moves within an object. Currently, only axes and axes objects seem to be supported for UIFigures.
iptPointerManager(hFigure,'enable') enables the figure’s pointer manager and updates it to recognize the newly added pointer behaviors.
The snippet below can be placed in the app’s startup function to change the pointer to crosshairs when the pointer enters the outerposition of a uiaxes and then change it back to the default arrow when it leaves the uiaxes.
% Define pointer behavior when pointer enter axes pm.enterFcn = @(~,~) set(app.UIFigure, 'Pointer', 'crosshair'); pm.exitFcn = @(~,~) set(app.UIFigure, 'Pointer', 'arrow'); pm.traverseFcn = []; iptSetPointerBehavior(app.UIAxes, pm)
% Enable pointer manager for app iptPointerManager(app.UIFigure,'enable');
Any function can be triggered when entering/exiting an axes object which makes the pointer management tools quite powerful. This snippet below defines a custom function cursorPositionFeedback() that responds to the pointer entering/exiting a patch object plotted within the uiaxes. When the pointer enters the patch, the patch color is changed to red, the pointer is changed to double arrows, and text appears in the app’s text area. When the pointer exits, the patch color changes back to blue, the pointer changes back to crosshairs, and the text area is cleared.
% Plot patch on uiaxes hold(app.UIAxes, 'on') region1 = patch(app.UIAxes,[1.5 3.5 3.5 1.5],[0 0 5 5],'b','FaceAlpha',0.07,... 'LineWidth',2,'LineStyle','--','tag','region1');
% Define pointer behavior for patch pm.enterFcn = @(~,~) cursorPositionFeedback(app, region1, 'in'); pm.exitFcn = @(~,~) cursorPositionFeedback(app, region1, 'out'); pm.traverseFcn = []; iptSetPointerBehavior(region1, pm)
% Enable pointer manager for app iptPointerManager(app.UIFigure,'enable');
function cursorPositionFeedback(app, hobj, inout) % When inout is 'in', change hobj facecolor to red and update textbox. % When inout is 'out' change hobj facecolor to blue, and clear textbox. % Check tag property of hobj to identify the object. switch lower(inout) case 'in' facecolor = 'r'; txt = 'Inside region 1'; pointer = 'fleur'; case 'out' facecolor = 'b'; txt = ''; pointer = 'crosshair'; end hobj.FaceColor = facecolor; app.TextArea.Value = txt; set(app.UIFigure, 'Pointer', pointer) end
The app showing the demo below is attached.
![](/matlabcentral/discussions/uploaded_files/1096/pointerDemo.gif)
Part 3. Create your own custom pointer symbol
- Set the figure’s pointer property to ‘custom’.
- Set the figure’s PointerShapeCData property to the custom pointer matrix. A custom pointer is defined by a 16x16 or 32x32 matrix where NaN values are transparent, 1=black, and 2=white.
- Set the figure’s PointerShapeHotSpot to [m,n] where m and n are the coordinates that define the tip or "hotspot" of the matrix.
This demo uses the attached mat file to create a black hand pointer symbol.
iconData = load('blackHandPointer.mat'); uifig = uifigure(); uifig.Pointer = 'custom'; uifig.PointerShapeCData = iconData.blackHandIcon; uifig.PointerShapeHotSpot = iconData.hotspot;
![](/matlabcentral/discussions/uploaded_files/1099/blackHandPointer.gif)
Also see Jiro's pointereditor() function on the file exchange which allows you to draw your own pointer.
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/16412/image.jpeg)
![](https://www.mathworks.com/matlabcentral/discussions/uploaded_files/16417/image.jpeg)