주요 콘텐츠

Results for


Check out this 3D chart that won Visual Of The Year for 2024 by Visual Capitalist. It's a mashup between a 3D bubblechart and a categorical bar plot yet the only graphical components are the x-axis labels and the legend. Not only does it show relative proportions of material in a laptop but it also shows what the raw material looks like.
I love the idea of analog data visualization. I wonder if any readers have made a analog "chart".
It's frustrating when a long function or script runs and prints unexpected outputs to the command window. The line producing those outputs can be difficult to find.
Starting in R2024b, use dbstop to find the line with unsuppressed outputs!
Run this line of code before running the script or function. Execution will pause when the line is hit and the file will open to that line. Outputs that are intentionaly displayed by functions such as disp() or fprintf() will be ignored.
dbstop if unsuppressed output
To turn this off,
dbclear if unsuppressed output
How to leave feedback on a doc page
Leaving feedback is a two-step process. At the bottom of most pages in the MATLAB documentation is a star rating.
Start by selecting a star that best answers the question. After selecting a star rating, an edit box appears where you can offer specific feedback.
When you press "Submit" you'll see the confirmation dialog below. You cannot go back and edit your content, although you can refresh the page to go through that process again.
Tips on leaving feedback
  • Be productive. The reader should clearly understand what action you'd like to see, what was unclear, what you think needs work, or what areas were really helpful.
  • Positive feedback is also helpful. By nature, feedback often focuses on suggestions for changes but it also helps to know what was clear and what worked well.
  • Point to specific areas of the page. This helps the reader to narrow the focus of the page to the area described by your feedback.
What happens to that feedback?
Before working at MathWorks I often left feedback on documentation pages but I never knew what happens after that. One day in 2021 I shared my speculation on the process:
> That feedback is received by MathWorks Gnomes which are never seen nor heard but visit the MathWorks documentation team at night while they are sleeping and whisper selected suggestions into their ears to manipulate their dreams. Occassionally this causes them to wake up with a Eureka moment that leads to changes in the documentation.
I'd like to let you in on the secret which is much less fanciful. Feedback left in the star rating and edit box are collected and periodically reviewed by the doc writers who look for trends on highly trafficked pages and finer grain feedback on less visited pages. Your feedback is important and often results in improvements.
RGB triplet [0,1]
9%
RGB triplet [0,255]
12%
Hexadecimal Color Code
13%
Indexed color
16%
Truecolor array
37%
Equally unfamiliar with all-above
13%
추천 수: 2784
Are you a Simulink user eager to learn how to create apps with App Designer? Or an App Designer enthusiast looking to dive into Simulink?
Don't miss today's article on the Graphics and App Building Blog by @Robert Philbrick! Discover how to build Simulink Apps with App Designer, streamlining control of your simulations!
Welcome to MATLAB Central's first Ask Me Anything (AMA) session! Over the next few weeks, I look forward to addressing any questions or curiosities you might have about MATLAB, the forum, sasquatches, or whatever's on your mind. Having volunteered as a contributor to this community before joining MathWorks, I'm excited to act as a bridge between these two worlds. Let's kick things off by sharing a little-known fact about the forum’s staff contributors!
A couple of years ago, before I joined MathWorks as a developer on the Graphics and Charting team, I often wondered who were the MathWorkers with the [staff] moniker answering questions in the Answers forum. Is their MATLAB Central activity part of their day-to-day job expectations? Do they serve specific roles on some kind of community outreach team? Is their work in the forum voluntary in the same way that non-staff contributors volunteer their time?
Now that I'm on the inside, I'd like to share a secret with my fellow MATLAB users and MATLAB Central enthusiasts: with the exception of the MathWorks Support Team, staff participation in the Answers forum is completely voluntary! The staff contributions you see in the forum arise from pure intrinsic motivation to connect with users, help people out of ruts, and spread the word about our product!
For example, Steven Lord has contributed 20-150 answers per month for 9 years! Steven is a quality engineer for core MATLAB numerical functions. Cris LaPierre develops training material and has been a faithful contributor in the forum for almost 6 years! Kojiro Saito and Akira Agata have been tackling Japanese content for more than 7 years! There are many others who have inspired me as a user, and I am honored to now call colleagues: Peter Perkins, Michio, Joss Knight, Alan Weiss, Jiro Doke, Edric Ellis, and many others who deserve appreciation.
The forum's success hinges on the invaluable contributions from the majority of non-staff volunteers, whose dedication and expertise fuel our community. But I know I wasn't alone in wondering about these staff contributors, so now you're in on the secret!
I'm curious to know what other topics you're interested in learning about. Ask me anything!
Temporary print statements are often helpful during debugging but it's easy to forget to remove the statements or sometimes you may not have writing privileges for the file. This tip uses conditional breakpoints to add print statements without ever editing the file!
What are conditional breakpoints?
Conditional breakpoints allow you to write a conditional statement that is executed when the selected line is hit and if the condition returns true, MATLAB pauses at that line. Otherwise, it continues.
The Hack: use ~fprintf() as the condition
fprintf prints information to the command window and returns the size of the message in bytes. The message size will always be greater than 0 which will always evaluate as true when converted to logical. Therefore, by negating an fprintf statement within a conditional breakpoint, the fprintf command will execute, print to the command window, and evalute as false which means the execution will continue uninterupted!
How to set a conditional break point
1. Right click the line number where you want the condition to be evaluated and select "Set Conditional Breakpoint"
2. Enter a valid MATLAB expression that returns a logical scalar value in the editor dialog.
Handy one-liners
Check if a line is reached: Don't forget the negation (~) and the line break (\n)!
~fprintf('Entered callback function\n')
Display the call stack from the break point line: one of my favorites!
~fprintf('%s\n',formattedDisplayText(struct2table(dbstack)))
Inspect variable values: For scalar values,
~fprintf('v = %.5f\n', v)
Use formattedDisplayText to convert more complex data to a string
~fprintf('%s\n', formattedDisplayText(v)).
Make sense of frequent hits: In some situations such as responses to listeners or interactive callbacks, a line can be executed 100s of times per second. Incorporate a timestamp to differentiate messages during rapid execution.
~fprintf('WindowButtonDownFcn - %s\n', datetime('now'))
Closing
This tip not only keeps your code clean but also offers a dynamic way to monitor code execution and variable states without permanent modifications. Interested in digging deeper? @Steve Eddins takes this tip to the next level with his Code Trace for MATLAB tool available on the File Exchange (read more).
Summary animation
To reproduce the events in this animation:
% buttonDownFcnDemo.m
fig = figure();
tcl = tiledlayout(4,4,'TileSpacing','compact');
for i = 1:16
ax = nexttile(tcl);
title(ax,"#"+string(i))
ax.ButtonDownFcn = @axesButtonDownFcn;
xlim(ax,[-1 1])
ylim(ax,[-1,1])
hold(ax,'on')
end
function axesButtonDownFcn(obj,event)
colors = lines(16);
plot(obj,event.IntersectionPoint(1),event.IntersectionPoint(2),...
'ko','MarkerFaceColor',colors(obj.Layout.Tile,:))
end
Adam Danz
Adam Danz
Last activity 2024년 3월 22일

The MATLAB command window isn't just for commands and outputs—it can also host interactive hyperlinks. These can serve as powerful shortcuts, enhancing the feedback you provide during code execution. Here are some hyperlinks I frequently use in fprintf statements, warnings, or error messages.
1. Open a website.
msg = "Could not download data from website.";
url = "https://blogs.mathworks.com/graphics-and-apps/";
hypertext = "Go to website"
fprintf(1,'%s <a href="matlab: web(''%s'') ">%s</a>\n',msg,url,hypertext);
Could not download data from website. Go to website
2. Open a folder in file explorer (Windows)
msg = "File saved to current directory.";
directory = cd();
hypertext = "[Open directory]";
fprintf(1,'%s <a href="matlab: winopen(''%s'') ">%s</a>\n',msg,directory,hypertext)
File saved to current directory. [Open directory]
3. Open a document (Windows)
msg = "Created database.csv.";
filepath = fullfile(cd,'database.csv');
hypertext = "[Open file]";
fprintf(1,'%s <a href="matlab: winopen(''%s'') ">%s</a>\n',msg,filepath,hypertext)
Created database.csv. [Open file]
4. Open an m-file and go to a specific line
msg = 'Go to';
file = 'streamline.m';
line = 51;
fprintf(1,'%s <a href="matlab: matlab.desktop.editor.openAndGoToLine(which(''%s''), %d); ">%s line %d</a>', msg, file, line, file, line);
5. Display more text
msg = 'Incomplete data detected.';
extendedInfo = '\tFilename: m32c4r28\n\tDate: 12/20/2014\n\tElectrode: (3,7)\n\tDepth: ???\n';
hypertext = '[Click for more info]';
warning('%s <a href="matlab: fprintf(''%s'') ">%s</a>', msg,extendedInfo,hypertext);
Warning: Incomplete data detected. [Click for more info]
<click>
  • Filename: m32c4r28
  • Date: 12/20/2014
  • Electrode: (3,7)
  • Depth: ???
6. Run a function
Similarly, you can also add hyperlinks in figures and apps
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
Adam Danz
Adam Danz
Last activity 2023년 10월 13일

Over the weekend I came across a pi approximation using durations of years and weeks (image below, Wolfram, eq. 89), accurate to 6 digits using the average Gregorian year (365.2425 days).
Here it is in MATLAB. I divided by 1 week at the end rather than multiplying by its reciprocal because you can’t divide a numeric by a duration in MATLAB (1/week).
weeks = @(n)n*days(7);
piApprox = ((years(13)-weeks(6))/years(13) + weeks(3)) / weeks(1)
% piApprox = 3.141593493469302
Here’s a breakdown
  • The first argument becomes 12.885 yrs / 13 yrs or 0.99115
  • Add three weeks: 0.99115 + 3 weeks = 21.991 days
  • The reduced fraction becomes 21.991 days / 7 days
Now it looks a lot closer to the more familiar approximation for pi 22/7 but with greater precision!
Adam Danz
Adam Danz
Last activity 2024년 3월 6일

I'm curious how the community uses the hold command when creating charts and graphics in MATLAB. In short, hold on sets up the axes to add new objects to the axes while hold off sets up the axes to reset when new objects are added.
When you use hold on do you always follow up with hold off? What's your reasoning on this decision?
Can't wait to discuss this here! I'd love to hear from newbies and experts alike!
figure out what my old code does
18%
write code comments for future me
11%
address a code analyzer warning
3%
reflect on the skills I've gained
8%
get food on my mouse and keyboard
38%
All of the above
22%
추천 수: 16434
New in R2022b: GridSizeChangedFcn
tiledlayout() creates a TiledChartLayout object that defines a gridded layout of axes within a figure. When using the 'flow' option, the grid size becomes dynamic and updates as axes are added or as the figure size changes. These features were introduced in R2019b and if you're still stuck on using subplot, you're missing out on several other great features of tiledlayout.
Starting in MATLAB R2022b you can define a callback function that responds to changes to the grid size in flow arrangements by setting the new gridSizeChangedFcn.
Use case
I often use a global legend to represent data across all axes within a figure. When the figure is tall and narrow, I want the legend to be horizontally oriented at the bottom of the figure but when the figure is short and wide, I prefer a vertically oriented legend on the right of the figure. By using the gridSizeChangedFcn, now I can update the legend location and orientation when the grid size changes.
Demo
gridSizeChangeFcn works like all other graphics callback functions. In this demo, I've named the gridSizeChangedFcn "updateLegendLayout", assigned by an anonymous function. The first input is the TiledChartLayout object and the second input is the event object that indicates the old and new grid sizes. The legend handle is also passed into the function. Since all of the tiles contain the same groups of data, the legend is based on data in the last tile.
As long as the legend is valid, the gridSizeChangedFcn updates the location and orientation of the legend so that when the grid is tall, the legend will be horizontal at the bottom of the figure and when the grid is wide, the legend will be vertical at the right of the figure.
Since the new grid size is available as a property in the TiledChartLayout object, I chose not to use the event argument. This way I can directly call the callback function at the end to update the legend without having to create an event.
Run this example from an m-file. Then change the width or height of the figure to demonstrate the legend adjustments.
% Prepare data
data1 = sort(randn(6))*10;
data2 = sort(randn(6))*10;
labels = ["A","B","C","D","E","F"];
groupLabels = categorical(["Control", "Test"]);
% Generate figure
fig = figure;
tcl = tiledlayout(fig, "flow", TileSpacing="compact", Padding="compact");
nTiles = height(data1);
h = gobjects(1,nTiles);
for i = 1:nTiles
ax = nexttile(tcl);
groupedData = [data1(i,:); data2(i,:)];
h = bar(ax,groupLabels, groupedData, "grouped");
title(ax,"condition " + i)
end
title(tcl,"GridSizeChangedFcn Demo")
ylabel(tcl,"Score")
legh = legend(h, labels);
title(legh,"Factors")
% Define and call the GridSizeChangeFcn
tcl.GridSizeChangedFcn = @(tclObj,event)updateLegendLayout(tclObj,event,legh);
updateLegendLayout(tcl,[],legh);
% Manually resize the vertical and horizontal dimensions of the figure
function updateLegendLayout(tclObj,~,legh)
% Evoked when the TiledChartLayout grid size changes in flow arrangements.
% tclObj - TiledChartLayout object
% event - (unused in this demo) contains old and new grid size
% legh - legend handle
if isgraphics(legh,'legend')
if tclObj.GridSize(1) > tclObj.GridSize(2)
legh.Layout.Tile = "south";
legh.Orientation = "horizontal";
else
legh.Layout.Tile = "east";
legh.Orientation = "vertical";
end
end
end
Give it a shot in MATLAB R2022b
  • Replace the legend with a colorbar to update the location and orientation of the colorbar.
  • Define a GridSizeChangedFcn within the loop so that it is called every time a tile is added.
  • Create a figure with many tiles (~20) and dynamically set a color to each row of axes.
  • Assign xlabels only to the bottom row of tiles and ylabels to only the left column of tiles.
Learn about other new features
This article is attached as a live script.
Uniform spacing and the problem of round-off error
The vector [3 4 5 6 7 8 9] is uniformly spaced with a step size of 1. So is [3 2 1 0 -1 -2] but with a step size of -1.
The vector [1 2 4 8] is not uniformly spaced.
A vector v with uniform spacing has the same finite interval or step size between consecutive elements of the vector. But sometimes round-off error poses a problem in calculating uniformity.
Take, for example, the vector produced by
format shortg
v = linspace(1,9,7)
v = 1x7
1 2.3333 3.6667 5 6.3333 7.6667 9
Linspace produces linearly spaced vectors but the intervals between elements of v, computed by diff(v), are not identical.
dv = diff(v)
dv = 1x6
1.3333 1.3333 1.3333 1.3333 1.3333 1.3333
dv == dv(1)
ans = 1×6 logical array
1 0 0 1 0 1
diff(dv)
ans = 1x5
4.4409e-16 0 -4.4409e-16 8.8818e-16 -8.8818e-16
Some extra steps are therefore necessary to set a tolerance that ignores error introduced by floating point arithmetic.
New in R2022b: isuniform
Determining uniformity of a vector became a whole lot easier in MATLAB R2022b with the new isuniform function.
isuniform returns a logical scalar indicating whether vector v is uniformly spaced within a round-off tolerance and returns the step size (or NaN if v is not uniform).
Let's look at the results for our vector v,
[tf,step] = isuniform(v)
tf = logical
1
step =
1.3333
How about non-uniformly spaced vector?
[tf,step] = isuniform(logspace(1,5,4))
tf = logical
0
step =
NaN
Give it a shot in MATLAB R2022b
  • What happens when all elements of v are equal?
  • Can you produce a vector with uniform spacing without using colons or linspace?
  • What additional steps would be needed to use isuniform with circular data?
References
This article is attached as a live script.
Never, I don't typically share code
46%
Never, even when my code is shared
14%
Occasionally
15%
Sometimes
8%
More often than not
5%
Always or almost always
12%
추천 수: 8896



20 minutes makes a difference

I struggled to learn MATLAB at first. A colleague at my university gave me about 20 minutes of his time to show me some basic features, how to reference the documentation, and how to debug code. That was enough for me to start using MATLAB independently. After a few semesters of developing analyses and visualizations, I started answering questions in the forum when I had time. I became addicted to volunteering and learning from the breadth of analytical problems the forum exposed me to.



Have you ever solved a problem using a MathWorks product?

If your answer is YES, you may be the right person to help someone looking for guidance to solve a similar problem. Some answers in the MATLAB Central community forum maintain 1000s of views per month and some files on the File Exchange have 1000s of downloads. Volunteering a moment of your time to answer a question or to share content to the File Exchange may benefit countless individuals in the near and distant future and you will likely learn a lot by contributing too!

  • 3616 questions were asked last month in the forum and in that time, 747 volunteers answered at least one question!
  • 62% of those volunteers were first-time contributors!
  • 335 volunteer contributors shared content in the File Exchange last month!
  • 1: the number of contributions it takes to make a difference.

This week is National Volunteer Week in the USA (April 17-23). Challenge yourself and your colleagues by committing to help a stranger break barriers in their path to learning MATLAB.



How to volunteer and contribute to the MATLAB Central Community

Here are two easy ways to accept the volunteer challenge.

Contribute to the MATLAB Answers Forum

  1. Go to the MATLAB Answers repository. This page shows all unanswered questions starting with the most recent question. Use the filters on the left to see answered questions or questions belonging to a specific category. Alternatively, search for questions using keywords in the search field or visit the landing page.
  2. Open a few questions that interest you based on the question titles and tags.
  3. Decide how you'd like to contribute. Sometimes a question needs refinement or requires a bit of work to address. Decide whether to leave a comment that guides the user in the right direction, answer the question, or skip to the next question. The decision tree below is how some experienced contributors approach these decisions.

Pro tips

  • Newer questions have more traffic and are often answered within an hour or minutes.
  • Multiple answers often add valuable alternative perspectives and solutions.
  • Sometimes answers aren't accepted or the asker disappears. Be not discouraged. Your answer holds much value.



Contribute to the File Exchange

  1. Choose a function, script, demo, or toolbox you created that may be helpful to the community.
  2. Go to the MathWorks File Exchange. Search for submissions that are similar to your idea and decide whether your idea adds value.
  3. Prepare your code for open-source sharing. The best submissions include brief documentation that explains the purpose of the code, inputs, expected outputs and limitations.
  4. Use the "Publish your code" button from the link above. This will guide you through the submission process.



Make a difference

No matter what level you are at as a MATLAB developer, you have skills that others around you could benefit from learning. Take the challenge and become a giant.

Let us know about your experience with MATLAB Central volunteers or your experience becoming a MATLAB Central volunteer in the comments below!

Don't waste time searching-just ask
6%
A few minutes or 1-2 searches
21%
A few hours, most Qs aren't unique
40%
Days-asking for help is last resort
14%
Infinite. I'll never ask a question
20%
추천 수: 23801

.

MATLAB R2022a provides app developers more control over user navigation through app components using the keyboard's Tab key.

Part 1. The new focus function: programmatically set keyboard focus to a UI component

Part 2. Modify focus order of components

Today we'll review Part 2. See yesterday's Community Highlight for Part 1.

-------------------------------------------------------------------------------------------------

Well-designed apps have an obvious flow through interactive fields and, as we learned yesterday, using the Tab key to move the focus to the next UI component is faster and more efficient than using a mouse. Here we'll learn how to read and set the tab order of UI components in an app.

Understanding tab and stacking order

By default, tab order in MATLAB apps is controlled by the stacking order in the Component Browser. Initially, the stacking order within the component browswer is based on the sequence in which the objects were added to the container object within the app. MATLAB R2020b gave us control to edit the stacking order by selecting a component and using either the Reorder tool from the Canvas toolstrip or by right-clicking the component and selecting Reorder from the context menu [1]. Tab order flows from bottom to top through the Component Browswer hierarchy for objects that are focusable. Sending a component backward within the stack sets its tab order to earlier relative to other components.

Setting tab focus order in R2022a

Three additional tab order features were added in MATLAB R2022a that make it easier to control app navigation with the Tab key.

1. Sort and Filter by Tab Order : Instead of using the Reorder tool which lists components in reverse tab-order and includes components that are not focusable, filter the list by focusable components and sort them by tab-order using the View dropdown menu within the Component Browser (label 1 in image below). From here, you can drag and drop components to set their tab (and stacking) order.

2. Auto Tab Order : To automatically sort focusable components within your app so that the tab order is from left-to-right and then top-to-bottom, in App Designer, from Design View, select the Canvas tab > Tab Order button > Apply Auto Tab Order (label 2 in image below). Alternatively, you can apply auto tab order to components within a container such as a uipanel or uitab by right-clicking on the container within the Component Browser and selecting Apply Auto Tab Order.

3. Visualize Tab Order : You no longer have to read and interpret the handle names in the component browser to understand the current tab order of UI components. Instead, view an animation of tab order within App Designer. From Design View, select the Canvas tab > Tab Order button > Visualize Tab Order (label 3 in image below).

.

Contextual focus control: the power of combining focus() with setting tab order

Yesterday's Community Highlight showed how to programmatically set UI component focus using the focus(c) function. This, combined with control of tab order, allows app developers to implement contextual focus control. For example, when a radio button is selected in the GIF below, the corresponding UI Tab is selected programmatically and the keyboard focus is set to the first component within the UI Tab thus allowing the user to smoothly continue keyboard navigation. This is achieved by a callback function that responds to changes in the Button Group that sets the SelectedTab property of the TabGroup and uses the new focus() function. For details, see the attached focusAndTabOrderDemo.mlapp.

-------------------------------------------------------------------------------------------------

Stay tuned

Follow Community Highlights to get notifications for new content.

Let us know what interests you in the new MATLAB R2022a release in the comment section below.

See also

Footnotes

[1] R202b release notes: change the stacking order of UI components

This Community Highlight is attached as a live script.

.

MATLAB R2022a provides app developers more control over user navigation through app components using the keyboard's Tab key.

Part 1. The new focus function: programmatically set keyboard focus to a UI component

Part 2. Modify focus order of components

Today we'll review Part 1. Come back tomorrow for Part 2.

-------------------------------------------------------------------------------------------------

Programmatically set UI component focus

Did you know that you can save ~2 seconds every time you use a keyboard shortcut rather than reaching for your mouse [1,2]?

I need you to focus here: starting in MATLAB R2022a, use the new focus function to set keyboard focus to a specific UI component.

By specifying the component handle ( c ) in focus(c),

  1. The figure containing the component is displayed
  2. A blue frame appears around the component
  3. The user can directly interact with the component.

.

Which components are focusable?

Focusable components are those that a user can interact with using the keyboard. So an object set to Enable='off' or Visible='off' cannot be in focus. See the documentation for more details.

What will you do with all of that extra time saved?

-------------------------------------------------------------------------------------------------

Stay tuned

Tomorrow we'll learn how to apply the new focus function with control of tab order to create contextual flow of UI component focus. Follow Community Highlights to get notifications.

Let us know what interests you in the new MATLAB R2022a release in the comment section below.

See also

Footnotes

[1] Lane et. al. (2005). International Journal of Human-Computer Interaction, 18(2).

[2] Michels (2018). median.com

This Community Highlight is attached as a live script.