メインコンテンツ

Results for


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

You've spent hours designing the perfect figure and now it's time to add it to a presentation or publication but the font sizes in the figure are too small to see for the people in the back of the room or too large for the figure space in the publication. You've got titles, subtitles, axis labels, legends, text objects, and other labels but their handles are inaccessible or scattered between several blocks of code. Making your figure readable no longer requires digging through your code and setting each text object's font size manually.

Starting in MATLAB R2022a, you have full control over a figure's font sizes and font units using the new fontsize function (see release notes ).

Use fontsize() to

  • Set FontSize and FontUnits properties for all text within specified graphics objects
  • Incrementally increase or decrease font sizes
  • Specify a scaling factor to maintain relative font sizes
  • Reset font sizes and font units to their default values . Note that the default font size and units may not be the same as the font sizes/units set directly with your code.

When specifying an object handle or an array of object handles, fontsize affects the font sizes and font units of text within all nested objects.

While you're at it, also check out the new fontname function that allows you to change the font name of objects in a figure!

Give the new fontsize function a test drive using the following demo figure in MATLAB R2022a or later and try the following commands:

% Increase all font sizes within the figure by a factor of 1.5
fontsize(fig, scale=1.5)
% Set all font sizes in the uipanel to 16
fontsize(uip, 16, "pixels")
% Incrementally increase the font sizes of the left two axes (x1.1)
% and incrementally decrease the font size of the legend (x0.9)
fontsize([ax1, ax2], "increase")
fontsize(leg, "decrease")
% Reset the font sizes within the entire figure to default values
fontsize(fig, "default")
% Create fake behavioral data
rng('default')
fy = @(a,x)a*exp(-(((x-8).^2)/(2*3.^2)));
x = 1 : 0.5 : 20;
y = fy(32,x);
ynoise = y+8*rand(size(y))-4;
selectedTrial = 13;
% Plot behavioral data
fig = figure('Units','normalized','Position',[0.1, 0.1, 0.4, 0.5]);
movegui(fig, 'center')
tcl = tiledlayout(fig,2,2); 
ax1 = nexttile(tcl); 
hold(ax1,'on')
h1 = plot(ax1, x, ynoise, 'bo', 'DisplayName', 'Response');
h2 = plot(ax1, x, y, 'r-', 'DisplayName', 'Expected');
grid(ax1, 'on')
title(ax1, 'Behavioral Results')
subtitle(ax1, sprintf('Trial %d', selectedTrial))
xlabel(ax1, 'Time (seconds)','Interpreter','Latex')
ylabel(ax1, 'Responds ($\frac{deg}{sec}$)','Interpreter','Latex')
leg = legend([h1,h2]);
% Plot behavioral error
ax2 = nexttile(tcl,3);
behavioralError = ynoise-y; 
stem(ax2, x, behavioralError)
yline(ax2, mean(behavioralError), 'r--', 'Mean', ...
    'LabelVerticalAlignment','bottom')
grid(ax2, 'on')
title(ax2, 'Behavioral Error')
subtitle(ax2, ax1.Subtitle.String)
xlabel(ax2, ax1.XLabel.String,'Interpreter','Latex')
ylabel(ax2, 'Response - Expected ($\frac{deg}{sec}$)','Interpreter','Latex')
% Simulate spike train data
ntrials = 25; 
nSamplesPerSecond = 3; 
nSeconds = max(x) - min(x); 
nSamples = ceil(nSeconds*nSamplesPerSecond);
xTime = linspace(min(x),max(x), nSamples);
spiketrain = round(fy(1, xTime)+(rand(ntrials,nSamples)-.5));
[trial, sample] = find(spiketrain);
time = xTime(sample);
% Spike raster plot
axTemp = nexttile(tcl, 2, [2,1]);
uip = uipanel(fig, 'Units', axTemp.Units, ...
    'Position', axTemp.Position, ...
    'Title', 'Neural activity', ...
    'BackgroundColor', 'W');
delete(axTemp)
tcl2 = tiledlayout(uip, 3, 1);
pax1 = nexttile(tcl2); 
plot(pax1, time, trial, 'b.', 'MarkerSize', 4)
yline(pax1, selectedTrial-0.5, 'r-', ...
    ['\leftarrow Trial ',num2str(selectedTrial)], ...
    'LabelHorizontalAlignment','right', ...
    'FontSize', 8); 
linkaxes([ax1, ax2, pax1], 'x')
pax1.YLimitMethod = 'tight';
title(pax1, 'Spike train')
xlabel(pax1, ax1.XLabel.String)
ylabel(pax1, 'Trial #')
% Show MRI
pax2 = nexttile(tcl2,2,[2,1]); 
[I, cmap] = imread('mri.tif');
imshow(I,cmap,'Parent',pax2)
hold(pax2, 'on')
th = 0:0.1:2*pi; 
plot(pax2, 7*sin(th)+84, 5*cos(th)+90, 'r-','LineWidth',2)
text(pax2, pax2.XLim(2), pax2.YLim(1), 'ML22a',...
    'FontWeight', 'bold', ...
    'Color','r', ...
    'VerticalAlignment', 'top', ...
    'HorizontalAlignment', 'right', ...
    'BackgroundColor',[1 0.95 0.95])
title(pax2, 'Area of activation')
% Overall figure title
title(tcl, 'Single trial responses')

This Community Highlight is attached as a live script.

This is not a question, but a point of discussion for the entire community. I am aware that every 1/2 months this theme comes out, but until this is not fixed it is totally necessary that this comes, indeed, out. And I said "fix" because Mathworks has to understand that a dark theme is not only a visual/aesthetic matter, it is a substantial part of the game. Most of the OS, GUIs, programs are actually in dark mode, and a vast majority of the users makes indeed use of a global dark mode. How much one does like it is personal, but the benefits to power savings and eye health is instead a fact. Mathworks being ignoring this for years is nothing but ridiculous. Of course it is not an easy task, but every minute of committment for it is worthy. And nope, Schemer is not helpful because it does not provide a real fix to this question.
I feel free to suggest something similar to the Spyder's dark theme, which came out like 2 years ago if I remember correctly.
Of course, my point is not being disrespectful (I am instead very respectful to the huge efforts of Mathworks for making this wonderful program run). But, form a user's point of view, the fact that not a single word has so far come out from Mathworks about a dark theme (meaning that for sure we will not see it in a timing of months) requires us to put a strong pressure on this.
Mathworks, please: it's time for a dark theme.
North America
23%
South America
3%
Europe
40%
Asia, Middle East, India
26%
Africa
4%
Australia, Oceania, or Other
4%
6178 票
Introduction
Comma-separated lists are really very simple. You use them all the time. Here is one:
a,b,c,d
That is a comma-separated list containing four variables, the variables a, b, c, and d. Every time you write a list separated by commas then you are writing a comma-separated list. Most commonly you would write a comma-separated list as inputs when calling a function:
fun(a,b,c,d)
or as arguments to the concatenation operator or cell construction operator:
[a,b,c,d]
{a,b,c,d}
or as function outputs:
[a,b,c,d] = fun();
It is very important to understand that in general a comma-separated list is NOT one variable (but it could be). However, sometimes it is useful to create a comma-separated list from one variable (or define one variable from a comma-separated list), and MATLAB has several ways of doing this from various container array types:
1) from a field of a structure array using dot-indexing:
struct_array.field % all elements
struct_array(idx).field % selected elements
2) from a cell array using curly-braces:
cell_array{:} % all elements
cell_array{idx} % selected elements
3) from a string array using curly-braces:
string_array{:} % all elements
string_array{idx} % selected elements
Note that in all cases, the comma-separated list consists of the content of the container array, not subsets (or "slices") of the container array itself (use parentheses to "slice" any array). In other words, they will be equivalent to writing this comma-separated list of the container array content:
content1, content2, content3, .. , contentN
and will return as many content arrays as the original container array has elements (or that you select using indexing, in the requested order). A comma-separated list of one element is just one array, but in general there can be any number of separate arrays in the comma-separated list (zero, one, two, three, four, or more). Here is an example showing that a comma-separated list generated from the content of a cell array is the same as a comma-separated list written explicitly:
>> C = {1,0,Inf};
>> C{:}
ans =
1
ans =
0
ans =
Inf
>> 1,0,Inf
ans =
1
ans =
0
ans =
Inf
How to Use Comma-Separated Lists
Function Inputs: Remember that every time you call a function with multiple input arguments you are using a comma-separated list:
fun(a,b,c,d)
and this is exactly why they are useful: because you can specify the arguments for a function or operator without knowing anything about the arguments (even how many there are). Using the example cell array from above:
>> vertcat(C{:})
ans =
1
0
Inf
which, as we should know by now, is exactly equivalent to writing the same comma-separated list directly into the function call:
>> vertcat(1,0,Inf)
ans =
1
0
Inf
How can we use this? Commonly these are used to generate vectors of values from a structure or cell array, e.g. to concatenate the filenames which are in the output structure of dir:
S = dir(..);
F = {S.name}
which is simply equivalent to
F = {S(1).name, S(2).name, S(3).name, .. , S(end).name}
Or, consider a function with multiple optional input arguments:
opt = {'HeaderLines',2, 'Delimiter',',', 'CollectOutputs',true);
fid = fopen(..);
C = textscan(fid,'%f%f',opt{:});
fclose(fid);
Note how we can pass the optional arguments as a comma-separated list. Remember how a comma-separated list is equivalent to writing var1,var2,var3,..., then the above example is really just this:
C = textscan(fid,'%f%f', 'HeaderLines',2, 'Delimiter',',', 'CollectOutputs',true)
with the added advantage that we can specify all of the optional arguments elsewhere and handle them as one cell array (e.g. as a function input, or at the top of the file). Or we could select which options we want simply by using indexing on that cell array. Note that varargin and varargout can also be useful here.
Function Outputs: In much the same way that the input arguments can be specified, so can an arbitrary number of output arguments. This is commonly used for functions which return a variable number of output arguments, specifically ind2sub and gradient and ndgrid. For example we can easily get all outputs of ndgrid, for any number of inputs (in this example three inputs and three outputs, determined by the number of elements in the cell array):
C = {1:3,4:7,8:9};
[C{:}] = ndgrid(C{:});
which is thus equivalent to:
[C{1},C{2},C{3}] = ndgrid(C{1},C{2},C{3});
Further Topics:
MATLAB documentation:
Click on these links to jump to relevant comments below:
Dynamic Indexing (indexing into arrays with arbitrary numbers of dimensions)
Nested Structures (why you get an error trying to index into a comma-separated list)
Summary
Just remember that in general a comma-separated list is not one variable (although they can be), and that they are exactly what they say: a list (of arrays) separated with commas. You use them all the time without even realizing it, every time you write this:
fun(a,b,c,d)
Yes, I'm it.
45%
No, someone else knows more.
55%
6563 票

Several major updates have been introduced to Answers’ reputation system! The updates include a new User Levels system, a new Editor indicator, and updated badges series.

1. User Levels

User Levels have become a best practice for many community sites to adopt. They help build trust in the community and provide recognition to contributors. There are 10 levels in the system and the labels will display next to users’ names throughout MATLAB Answers and on your community profile. We hope to see more users climb the ladder and level up!

2. Editor Indicators

Becoming an Editor (upon earning 3,000 points) is a huge milestone in Answers. Therefore, we introduced the Editor indicator to show our appreciation. From the screenshot below, you will notice a user can have both a User Level and an Editor indicator.

3. Updated Badge Series

Based on our analysis of existing badges, we decided to introduce 2 new badges into existing series and retire an entire badge series.

  • The Knowledgeable badge series and the Thankful badge series now have 5 levels.
  • The Revival badge series has been archived and is no longer being awarded. If you earned one of these badges, it would still show up in your community profile.

You will find more information on Answers help page . If you have any questions, comments or feedback, free feel to leave a comment below.

Cody is a useful tool to practice MATLAB skills not only by solving the problems but also learn from each other’s solutions. Sometimes you see subpar solutions that are cheats and hacks. With the flagging feature we released recently, you can help us identify solutions that administrators, including Community Advisory Board members, can review and delete.

How to flag?

Flag Options - Only available on solutions

Skiing
35%
Skating (including hockey)
21%
Sledding (luge, bobsled, etc.)
10%
Curling
19%
Biathlon (skiing + shooting)
15%
640 票
MATLAB (Way to go!!! You rock!)
49%
Python (not from within MATLAB)
29%
Any variation of C
12%
Java, Javascript
4%
R, Ruby, Swift, Go, Scala, PHP, VB
2%
Other not mentioned, or mixture
4%
10577 票
Ambient | Atmospheric | Nature
9%
Classical | Jazz | Musicals
10%
Electronic | Dubstep | House | VGM
15%
Lo-fi | Chill | Coffee House
22%
Rock | Metal | Pop | Punk | Hip Hop
27%
Other | Podcasts | Nothing
17%
753 票
I only use it for homework problems
22%
1
5%
2-10
24%
10-100
28%
More than 100
12%
None yet (just started learning)
9%
6646 票
1 (just me)
8%
2-10
9%
11-100
8%
More than 100 (e.g. University)
65%
I can't even guess.
9%
8483 票
1 monitor/screen
42%
2
46%
3
9%
4 or more
3%
12173 票
Windows
74%
Apple, Mac, iPad
13%
Android (MATLAB Online)
4%
iPhone (MATLAB Online)
1%
Unix, Linux, Ubuntu, etc.
6%
11570 票
Mike Croucher
Mike Croucher
Last activity 2022 年 1 月 17 日

Every day, thousands of people ask questions on MATLAB Answers and many of these are about their code. Questions such as “How can I make this faster?”, “Why do I get this error message?” or “Why don’t I get the answer I expect?”. There’s often one crucial thing missing though – the code in question!

Most of the people who answer questions on MATLAB Answers are volunteers from the community. They are answering your questions for fun, to learn more about MATLAB or just because they like to be helpful. This is even true for people such as me who are MathWorks members of staff. It’s not part of my role to patrol the community, looking where I can help out. I do it because I like to do it.

Make it easier to help me help you.

Imagine you’re a volunteer, looking for something interesting to answer. What kind of questions are you more likely to dig into and help an anonymous stranger figure out?

In my case, I almost always focus on problems that I can easily reproduce. I rarely know the answer to any question off the top of my head and so what I like to do is start off with the problem you are facing and use the various tools available to me such as the profiler or debugger to figure it out. This is the fun of it all for me – I almost always learn something by doing this and you get helped out as a side effect!

The easier I can reproduce your issue, the more likely I am to get started. If I can’t reproduce anything and the answer isn’t immediately obvious to me I’ll just move onto the next question. One example that demonstrates this perfectly is a case where someone’s MATLAB code was running too slowly. All of the code was available so I could run it on my machine, profile it and provide a speed-up of almost 150x.

It's not always feasible or desirable to post all of your code in which case you need to come up with a minimal, reproducible example. What’s the smallest amount of code and data you can post that I can run on my machine and see what you see? This may be more work for you but it will greatly increase your chances of receiving an answer to your question.

General web search
75%
Specific web search for MLC content
12%
I search directly within MLC
3%
Combination of choices 2 & 3
9%
Neither (please leave a comment)
1%
813 票
My school supplies me as a student
63%
School bought it (prof, staff,etc.)
10%
I bought my own (student, home, etc
5%
My company/gov't/organization
17%
I'm using a free trial right now.
4%
Gift from someone (e.g. Mathworks)
1%
17288 票
Less than 1 hour
17%
1-2 hours
17%
2-3 hours
16%
3-4 hours
14%
More than 4 hours per day
36%
1174 票
Image Analyst
Image Analyst
Last activity 2022 年 4 月 7 日

White and gold
32%
Blue and black
42%
I can see it both ways, depending
16%
Not sure or something else/neither
10%
419 票