Ideas
フォロー



As pointed out in Doxygen comments in code generated with Simulink Embedded Coder - MATLAB Answers - MATLAB Central (mathworks.com), it would be nice that Embedded Coder has an option to generate Doxygen-style comments for signals of buses, i.e.:
/** @brief <Signal desciption here> **/
This would allow static analysis tools to parse the comments. Please add that feature!
In the past two years, MATHWORKS has updated the image viewer and audio viewer, giving them a more modern interface with features like play, pause, fast forward, and some interactive tools that are more commonly found in typical third-party players. However, the video player has not seen any updates. For instance, the Video Viewer or vision.VideoPlayer could benefit from a more modern player interface. Perhaps I haven't found a suitable built-in player yet. It would be great if there were support for custom image processing and audio processing algorithms that could be played in a more modern interface in real time.
Additionally, I found it quite challenging to develop a modern video player from scratch in App Designer.(If there's a video component for that that would be great)
-----------------------------------------------------------------------------------------------------------------
BTW,the following picture shows the built-in function uihtml function showing a more modern playback interface with controls for play, pause and so on. But can not add real-time image processing algorithms within it.
As far as I know, starting from MATLAB R2024b, the documentation is defaulted to be accessed online. However, the problem is that every time I open the official online documentation through my browser, it defaults or forcibly redirects to the documentation hosted site for my current geographic location, often with multiple pop-up reminders, which is very annoying!
Suggestion: Could there be an option to set preferences linked to my personal account so that the documentation defaults to my chosen language preference without having to deal with “forced reminders” or “forced redirection” based on my geographic location? I prefer reading the English documentation, but the website automatically redirects me to the Chinese documentation due to my geolocation, which is quite frustrating!
Chris Hooper
Chris Hooper
Last activity 2024 年 8 月 29 日

isequaln exists to return true when NaN==NaN.
unique treats NaN==NaN as false (as it should) requiring NaN to be replaced if NaN is not considered unique in a particular application. In my application, I am checking uniqueness of table rows using [table_unique,index_unique]=unique(table,"rows","sorted") and would prefer to keep NaN as NaN or missing in table_unique without the overhead of replacing it with a dummy value then replacing it again. Dummy values also have the risk of matching existing values in the table, requiring first finding a dummy value that is not in the table.
uniquen (similar to isequaln) would be more eloquent.
Please point out if I am missing something!
Daniel Dolan
Daniel Dolan
Last activity 2024 年 8 月 7 日

Is anyone else disappointed with uifigures? It seems apparent that these will eventually replace traditional figures, but there is still so much that doesn't quite work. I've tinkered with uifigures since their introduction in release 2016a, but even in 2020a I can't reliably export a uifigure to a graphics file. Sure it works sometimes, but not if a uipanel is present. The exportgraphics command is not as powerful as the print command, leaving some graphic formats (such as *.svg and *.eps) unsupported. How do you generate graphic files of a specific size? You can't even use subplots without overriding the default AutoResizeChildren setting!
Everything with uifigures seems to be slower and less stable than the figure variant. App Designer is much better than GUIDE, but that is not exactly high praise. I would rather generate "apps" programatically across several files instead of dealing with a single-file class definition containing 1000+ lines.
Where is this transition going? MATLAB graphics are moving away from Java in favor of JavaScript, and I'm not sure that we are at all ready for that.
Edit: due to the increasing size of this thread, it is continued here.
What should you post where?
Wishlist threads (#1 #2 #3 #4 #5 #6): bugs and feature requests for Matlab Answers
Frustation threads (#1 #2): frustations about usage and capabilities of Matlab itself
Missing feature threads (#1 #2): features that you whish Matlab would have had
Next Gen threads (#1): features that would break compatibility with previous versions, but would be nice to have
@anyone posting a new thread when the last one gets too large (about 50 answers seems a reasonable limit per thread), please update this list in all last threads. (if you don't have editing privileges, just post a comment asking someone to do the edit)
This topic is for features you would like to see for the MATLAB Answers facility itself, and also for bug reports about the MATLAB Answers facility.
This topic is the follow on to the first Wish-list for MATLAB Answer sections and second MATLAB Answers Wish-list #2 (and bug reports). Those grew large enough to become unwieldy; and Mathworks has made enough changes to make a number of the past points no longer of relevance. More recently there was the limited purpose New design of the forum - grey on white which turned into a bug and wish list; I have renamed that for continuity.
I suggest one wish (or bug report) per answer, so that people can vote their wishes.
Emma Farnan
Emma Farnan
Last activity 2024 年 7 月 19 日

Several of the colormaps are great for a 256 color surface plot, but aren't well optimized for extracting m colors for plotting several independent lines. The issue is that many colormaps have start/end colors that are too similar or are suboptimal colors for lines. There are certainly many workarounds for this, but it would be a great quality of life to adjust that directly when calling this.
Example:
x = linspace(0,2*pi,101)';
y = [1:6].*cos(x);
figure; plot(x,y,'LineWidth',2); grid on; axis tight;
And now if I wanted to color these lines, I could use something like turbo(6) or gray(6) and then apply it using colororder.
colororder(turbo(6))
But my issue is that the ends of the colormap are too similar. For other colormaps, you may get lines that are too light to be visible against the white background. There are plenty of workarounds, with my preference being to create extra colors and truncate that before using colororder.
cmap = turbo(8); cmap = cmap(2:end-1,:); % Truncate the end colors
figure; plot(x,y,'LineWidth',2); grid on; axis tight;
colororder(cmap)
I think it would be really awesome to add some name-argument input pair to these colormaps that can specify the range you want so this could even be done inside the colororder calling if desired. An example of my proposed solution would look something like this:
cmap = turbo(6,'Range',[0.1 0.8]); % Proposed idea to add functionality
Where in this scenario, the resulting colormap would be 6 equally spaced colors that range from 10% to 80% of the total color range. This would be especially nice because you could more quickly modify the range of colors, or you could set the limits regardless of whether you need to plot 3, 6, or 20 lines.
Honzik
Honzik
Last activity 2024 年 7 月 18 日

I've noticed is that the highly rated fonts for coding (e.g. Fira Code, Inconsolata, etc.) seem to overlook one issue that is key for coding in Matlab. While these fonts make 0 and O, as well as the 1 and l easily distinguishable, the brackets are not. Quite often the curly bracket looks similar to the curved bracket, which can lead to mistakes when coding or reviewing code.
So I was thinking: Could Mathworks put together a team to review good programming fonts, and come up with their own custom font designed specifically and optimized for Matlab syntax?
Gregory Vernon
Gregory Vernon
Last activity 2024 年 7 月 13 日

Something that had bothered me ever since I became an FEA analyst (2012) was the apparent inability of the "camera" in Matlab's 3D plot to function like the "cameras" in CAD/CAE packages.
For instance, load the ForearmLink.stl model that ships with the PDE Toolbox in Matlab and ParaView and try rotating the model.
clear
close all
gm = importGeometry( "ForearmLink.stl" );
pdegplot(gm)
To provide talking points, here's a YouTube video I recorded.
Things to observe:
  1. Note that I cant seem to rotate continuously around the x-axis. It appears to only support rotations from [0, 360] as opposed to [-inf, inf]. So, for example, if I'm looking in the Y+ direction and rotate around X so that I'm looking at the Z- direction, and then want to look in the Y- direction, I can't simply keep rotating around the X axis... instead have to rotate 180 degrees around the Z axis and then around the X axis. I'm not aware of any data visualization applications (e.g., ParaView, VisIt, EnSight) or CAD/CAE tools with such an interaction.
  2. Note that at the 50 second mark, I set a view in ParaView: looking in the [X-, Y-, Z-] direction with Y+ up. Try as I might in Matlab, I'm unable to achieve that same view perspective.
Today I discovered that if one turns on the Camera Toolbar from the View menubar, then clicks the Orbit Camera icon, then the No Principal Axis icon:
That then it acts in the manner I've long desired. Oh, and also, for the interested, it is programmatically available: https://www.mathworks.com/help/matlab/ref/cameratoolbar.html
I might humbly propose this mode either be made more discoverable, similar to the little interaction widgets that pop up in figures:
Or maybe use the middle-mouse button to temporarily use this mode (a mouse setting in, e.g., Abaqus/CAE).
An option for 10th degree polynomials but no weighted linear least squares. Seriously? Jesse
A high school student called for help with this physics problem:
  • Car A moves with constant velocity v.
  • Car B starts to move when Car A passes through the point P.
  • Car B undergoes...
  • uniform acc. motion from P to Q.
  • uniform velocity motion from Q to R.
  • uniform acc. motion from R to S.
  • Car A and B pass through the point R simultaneously.
  • Car A and B arrive at the point S simultaneously.
Q1. When car A passes the point Q, which is moving faster?
Q2. Solve the time duration for car B to move from P to Q using L and v.
Q3. Magnitude of acc. of car B from P to Q, and from R to S: which is bigger?
Well, it can be solved with a series of tedious equations. But... how about this?
Code below:
%% get images and prepare stuffs
figure(WindowStyle="docked"),
ax1 = subplot(2,1,1);
hold on, box on
ax1.XTick = [];
ax1.YTick = [];
A = plot(0, 1, 'ro', MarkerSize=10, MarkerFaceColor='r');
B = plot(0, 0, 'bo', MarkerSize=10, MarkerFaceColor='b');
[carA, ~, alphaA] = imread('https://cdn.pixabay.com/photo/2013/07/12/11/58/car-145008_960_720.png');
[carB, ~, alphaB] = imread('https://cdn.pixabay.com/photo/2014/04/03/10/54/car-311712_960_720.png');
carA = imrotate(imresize(carA, 0.1), -90);
carB = imrotate(imresize(carB, 0.1), 180);
alphaA = imrotate(imresize(alphaA, 0.1), -90);
alphaB = imrotate(imresize(alphaB, 0.1), 180);
carA = imagesc(carA, AlphaData=alphaA, XData=[-0.1, 0.1], YData=[0.9, 1.1]);
carB = imagesc(carB, AlphaData=alphaB, XData=[-0.1, 0.1], YData=[-0.1, 0.1]);
txtA = text(0, 0.85, 'A', FontSize=12);
txtB = text(0, 0.17, 'B', FontSize=12);
yline(1, 'r--')
yline(0, 'b--')
xline(1, 'k--')
xline(2, 'k--')
text(1, -0.2, 'Q', FontSize=20, HorizontalAlignment='center')
text(2, -0.2, 'R', FontSize=20, HorizontalAlignment='center')
% legend('A', 'B') % this make the animation slow. why?
xlim([0, 3])
ylim([-.3, 1.3])
%% axes2: plots velocity graph
ax2 = subplot(2,1,2);
box on, hold on
xlabel('t'), ylabel('v')
vA = plot(0, 1, 'r.-');
vB = plot(0, 0, 'b.-');
xline(1, 'k--')
xline(2, 'k--')
xlim([0, 3])
ylim([-.3, 1.8])
p1 = patch([0, 0, 0, 0], [0, 1, 1, 0], [248, 209, 188]/255, ...
EdgeColor = 'none', ...
FaceAlpha = 0.3);
%% solution
v = 1; % car A moves with constant speed.
L = 1; % distances of P-Q, Q-R, R-S
% acc. of car B for three intervals
a(1) = 9*v^2/8/L;
a(2) = 0;
a(3) = -1;
t_BatQ = sqrt(2*L/a(1)); % time when car B arrives at Q
v_B2 = a(1) * t_BatQ; % speed of car B between Q-R
%% patches for velocity graph
p2 = patch([t_BatQ, t_BatQ, t_BatQ, t_BatQ], [1, 1, v_B2, v_B2], ...
[248, 209, 188]/255, ...
EdgeColor = 'none', ...
FaceAlpha = 0.3);
p3 = patch([2, 2, 2, 2], [1, v_B2, v_B2, 1], [194, 234, 179]/255, ...
EdgeColor = 'none', ...
FaceAlpha = 0.3);
%% animation
tt = linspace(0, 3, 2000);
for t = tt
A.XData = v * t;
vA.XData = [vA.XData, t];
vA.YData = [vA.YData, 1];
if t < t_BatQ
B.XData = 1/2 * a(1) * t^2;
vB.XData = [vB.XData, t];
vB.YData = [vB.YData, a(1) * t];
p1.XData = [0, t, t, 0];
p1.YData = [0, vB.YData(end), 1, 1];
elseif t >= t_BatQ && t < 2
B.XData = L + (t - t_BatQ) * v_B2;
vB.XData = [vB.XData, t];
vB.YData = [vB.YData, v_B2];
p2.XData = [t_BatQ, t, t, t_BatQ];
p2.YData = [1, 1, vB.YData(end), vB.YData(end)];
else
B.XData = 2*L + v_B2 * (t - 2) + 1/2 * a(3) * (t-2)^2;
vB.XData = [vB.XData, t];
vB.YData = [vB.YData, v_B2 + a(3) * (t - 2)];
p3.XData = [2, t, t, 2];
p3.YData = [1, 1, vB.YData(end), v_B2];
end
txtA.Position(1) = A.XData(end);
txtB.Position(1) = B.XData(end);
carA.XData = A.XData(end) + [-.1, .1];
carB.XData = B.XData(end) + [-.1, .1];
drawnow
end
Gregory Vernon
Gregory Vernon
Last activity 2024 年 5 月 6 日

Updating some of my educational Livescripts to 2024a, really love the new "define a function anywhere" feature, and have a "new" idea for improving Livescripts -- support "hidden" code blocks similar to the Jupyter Notebooks functionality.
For example, I often create "complicated" plots with a bunch of ancillary items and I don't want this code exposed to the reader by default, as it might confuse the reader. For example, consider a Livescript that might read like this:
-----
Noting the similar structure of these two mappings, let's now write a function that simply maps from some domain to some other domain using change of variable.
function x = ChangeOfVariable( x, from_domain, to_domain )
x = x - from_domain(1);
x = x * ( ( to_domain(2) - to_domain(1) ) / ( from_domain(2) - from_domain(1) ) );
x = x + to_domain(1);
end
Let's see this function in action
% HIDE CELL
clear
close all
from_domain = [-1, 1];
to_domain = [2, 7];
from_values = [-1, -0.5, 0, 0.5, 1];
to_values = ChangeOfVariable( from_values, from_domain, to_domain )
to_values = 1×5
2.0000 3.2500 4.5000 5.7500 7.0000
We can plot the values of from_values and to_values, showing how they're connected to each other:
% HIDE CELL
figure
hold on
for n = 1 : 5
plot( [from_values(n) to_values(n)], [1 0], Color="k", LineWidth=1 )
end
ax = gca;
ax.YTick = [];
ax.XLim = [ min( [from_domain, to_domain] ) - 1, max( [from_domain, to_domain] ) + 1 ];
ax.YLim = [-0.5, 1.5];
ax.XGrid = "on";
scatter( from_values, ones( 5, 1 ), Marker="s", MarkerFaceColor="flat", MarkerEdgeColor="k", SizeData=120, LineWidth=1, SeriesIndex=1 )
text( mean( from_domain ), 1.25, "$\xi$", Interpreter="latex", HorizontalAlignment="center", VerticalAlignment="middle" )
scatter( to_values, zeros( 5, 1 ), Marker="o", MarkerFaceColor="flat", MarkerEdgeColor="k", SizeData=120, LineWidth=1, SeriesIndex=2 )
text( mean( to_domain ), -0.25, "$x$", Interpreter="latex", HorizontalAlignment="center", VerticalAlignment="middle" )
scaled_arrow( ax, [mean( [from_domain(1), to_domain(1) ] ) - 1, 0.5], ( 1 - 0 ) / ( from_domain(1) - to_domain(1) ), 1 )
scaled_arrow( ax, [mean( [from_domain(end), to_domain(end)] ) + 1, 0.5], ( 1 - 0 ) / ( from_domain(end) - to_domain(end) ), -1 )
text( mean( [from_domain(1), to_domain(1) ] ) - 1.5, 0.5, "$x(\xi)$", Interpreter="latex", HorizontalAlignment="center", VerticalAlignment="middle" )
text( mean( [from_domain(end), to_domain(end)] ) + 1.5, 0.5, "$\xi(x)$", Interpreter="latex", HorizontalAlignment="center", VerticalAlignment="middle" )
-----
Where scaled_arrow is some utility function I've defined elsewhere... See how a majority of the code is simply "drivel" to create the plot, clear and close? I'd like to be able to hide those cells so that it would look more like this:
-----
Noting the similar structure of these two mappings, let's now write a function that simply maps from some domain to some other domain using change of variable.
function x = ChangeOfVariable( x, from_domain, to_domain )
x = x - from_domain(1);
x = x * ( ( to_domain(2) - to_domain(1) ) / ( from_domain(2) - from_domain(1) ) );
x = x + to_domain(1);
end
Let's see this function in action
Show code cell
from_domain = [-1, 1];
to_domain = [2, 7];
from_values = [-1, -0.5, 0, 0.5, 1];
to_values = ChangeOfVariable( from_values, from_domain, to_domain )
to_values = 1×5
2.0000 3.2500 4.5000 5.7500 7.0000
We can plot the values of from_values and to_values, showing how they're connected to each other:
Show code cell
-----
Thoughts?
I recently had issues with code folding seeming to disappear and it turns out that I had unknowingly disabled the "show code folding margin" option by accident. Despite using MATLAB for several years, I had no idea this was an option, especially since there seemed to be no references to it in the code folding part of the "Preferences" menu.
It would be great if in the future, there was a warning that told you about this when you try enable/disable folding in the Preferences.
I am using 2023b by the way.
Jérôme
Jérôme
Last activity 2024 年 4 月 29 日

In the MATLAB editor, when clicking on a variable name, all the other instances of the variable name will be highlighted.
But this does not work for structure fields, which is a pity. Such feature would be quite often useful for me.
I show an illustration below, and compare it with Visual Studio Code that does it. ;-)
I am using MATLAB R2023a, sorry if it has been added to newer versions, but I didn't see it in the release notes.
In short: support varying color in at least the plot, plot3, fplot, and fplot3 functions.
This has been a thing that's come up quite a few times, and includes questions/requests by users, workarounds by the community, and workarounds presented by MathWorks -- examples of each below. It's a feature that exists in Python's Matplotlib library and Sympy. Anyways, given that there are myriads of workarounds, it appears to be one of the most common requests for Matlab plots (Matlab's plotting is, IMO, one of the best features of the product), the request precedes the 21st century, and competitive tools provide the functionality, it would seem to me that this might be the next great feature for Matlab plotting.
I'm curious to get the rest of the community's thoughts... what's everyone else think about this?
---
User questions/requests
User-provided workarounds
MathWorks-provided workarounds
I would like to propose the creation of MATLAB EduHub, a dedicated channel within the MathWorks community where educators, students, and professionals can share and access a wealth of educational material that utilizes MATLAB. This platform would act as a central repository for articles, teaching notes, and interactive learning modules that integrate MATLAB into the teaching and learning of various scientific fields.
Key Features:
1. Resource Sharing: Users will be able to upload and share their own educational materials, such as articles, tutorials, code snippets, and datasets.
2. Categorization and Search: Materials can be categorized for easy searching by subject area, difficulty level, and MATLAB version..
3. Community Engagement: Features for comments, ratings, and discussions to encourage community interaction.
4. Support for Educators: Special sections for educators to share teaching materials and track engagement.
Benefits:
- Enhanced Educational Experience: The platform will enrich the learning experience through access to quality materials.
- Collaboration and Networking: It will promote collaboration and networking within the MATLAB community.
- Accessibility of Resources: It will make educational materials available to a wider audience.
By establishing MATLAB EduHub, I propose a space where knowledge and experience can be freely shared, enhancing the educational process and the MATLAB community as a whole.
Andrew Janke
Andrew Janke
Last activity 2024 年 3 月 13 日

Let's say MathWorks decides to create a MATLAB X release, which takes a big one-time breaking change that abandons back-compatibility and creates a more modern MATLAB language, ditching the unfortunate stuff that's around for historical reasons. What would you like to see in it?
I'm thinking stuff like syntax and semantics tweaks, changes to function behavior and interfaces in the standard library and Toolboxes, and so on.
(The "X" is for major version 10, like in "OS X". Matlab is still on version 9.x even though we use "R20xxa" release names now.)
What should you post where?
Wishlist threads (#1 #2 #3 #4 #5): bugs and feature requests for Matlab Answers
Frustation threads (#1 #2): frustrations about usage and capabilities of Matlab itself
Missing feature threads (#1 #2): features that you whish Matlab would have had
Next Gen threads (#1): features that would break compatibility with previous versions, but would be nice to have
@anyone posting a new thread when the last one gets too large (about 50 answers seems a reasonable limit per thread), please update this list in all last threads. (if you don't have editing privileges, just post a comment asking someone to do the edit)
Matt J
Matt J
Last activity 2024 年 3 月 1 日

Would it be a good thing to have implicit expansion enabled for cat(), horzcat(), vertcat()? There are often situations where I would like to be able to do things like this:
x=[10;20;30;40];
y=[11;12;13;14];
z=cat(3, 0,1,2);
C=[x,y,z]
with the result,
C(:,:,1) =
10 11 0
20 12 0
30 13 0
40 14 0
C(:,:,2) =
10 11 1
20 12 1
30 13 1
40 14 1
C(:,:,3) =
10 11 2
20 12 2
30 13 2
40 14 2
Antonello Zito
Antonello Zito
Last activity 2024 年 2 月 27 日

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.
lazymatlab
lazymatlab
Last activity 2024 年 2 月 20 日

2 x 2 행렬의 행렬식은
  • 행렬의 두 row 벡터로 정의되는 평행사변형의 면적입니다.
  • 물론 두 column 벡터로 정의되는 평행사변형의 면적이기도 합니다.
  • 좀 더 정확히는 signed area입니다. 면적이 음수가 될 수도 있다는 뜻이죠.
  • 행렬의 두 행(또는 두 열)을 맞바꾸면 행렬식의 부호도 바뀌고 면적의 부호도 바뀌어야합니다.
일반적으로 n x n 행렬의 행렬식은
  • 각 row 벡터(또는 각 column 벡터)로 정의되는 N차원 공간의 평행면체(?)의 signed area입니다.
  • 제대로 이해하려면 대수학의 개념을 많이 가지고 와야 하는데 자세한 설명은 생략합니다.(=저도 모른다는 뜻)
  • 더 자세히 알고 싶으시면 수학하는 만화의 '넓이 이야기' 편을 추천합니다.
  • 수학적인 정의를 알고 싶으시면 위키피디아를 보시면 됩니다.
  • 이렇게 생겼습니다. 좀 무섭습니다.
아래 코드는...
  • 2 x 2 행렬에 대해서 이것을 수식 없이 그림만으로 증명하는 과정입니다.
  • gif 생성에는 ScreenToGif를 사용했습니다. (gif 만들기엔 이게 킹왕짱인듯)
Determinant of 2 x 2 matrix is...
  • An area of a parallelogram defined by two row vectors.
  • Of course, same one defined by two column vectors.
  • Precisely, a signed area, which means area can be negative.
  • If two rows (or columns) are swapped, both the sign of determinant and area change.
More generally, determinant of n x n matrix is...
  • Signed area of parallelepiped defined by rows (or columns) of the matrix in n-dim space.
  • For a full understanding, a lot of concepts from abstract algebra should be brought, which I will not write here. (Cuz I don't know them.)
  • For a mathematical definition of determinant, visit wikipedia.
  • A little scary, isn't it?
The code below is...
  • A process to prove the equality of the determinant of 2 x 2 matrix and the area of parallelogram.
  • ScreenToGif is used to generate gif animation (which is, to me, the easiest way to make gif).
% 두 점 (a, b), (c, d)의 좌표
a = 4;
b = 1;
c = 1;
d = 3;
% patch 색 pre-define
lightgreen = [144, 238, 144]/255;
lightblue = [169, 190, 228]/255;
lightorange = [247, 195, 160]/255;
% animation params.
anim_Nsteps = 30;
% create window
figure('WindowStyle','docked')
ax = axes;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
ax.XTick = [];
ax.YTick = [];
hold on
ax.XLim = [-.4, a+c+1];
ax.YLim = [-.4, b+d+1];
% create ad-bc patch
area = patch([0, a, a+c, c], [0, b, b+d, d], lightgreen);
p_ab = plot(a, b, 'ko', 'MarkerFaceColor', 'k');
p_cd = plot(c, d, 'ko', 'MarkerFaceColor', 'k');
p_ab.UserData = text(a+0.1, b, '(a, b)', 'FontSize',16);
p_cd.UserData = text(c+0.1, d-0.2, '(c, d)', 'FontSize',16);
area.UserData = text((a+c)/2-0.5, (b+d)/2, 'ad-bc', 'FontSize', 18);
pause
%% Is this really ad-bc?
area.UserData.String = 'ad-bc...?';
pause
%% fade out ad-bc
fadeinout(area, 0)
area.UserData.Visible = 'off';
pause
%% fade in ad block
rect_ad = patch([0, a, a, 0], [0, 0, d, d], lightblue, 'EdgeAlpha', 0, 'FaceAlpha', 0);
uistack(rect_ad, 'bottom');
fadeinout(rect_ad, 1, t_pause=0.003)
draw_gridline(rect_ad, ["23", "34"])
rect_ad.UserData = text(mean(rect_ad.XData), mean(rect_ad.YData), 'ad', 'FontSize', 20, 'HorizontalAlignment', 'center');
pause
%% fade-in bc block
rect_bc = patch([0, c, c, 0], [0, 0, b, b], lightorange, 'EdgeAlpha', 0, 'FaceAlpha', 0);
fadeinout(rect_bc, 1, t_pause=0.0035)
draw_gridline(rect_bc, ["23", "34"])
rect_bc.UserData = text(b/2, c/2, 'bc', 'FontSize', 20, 'HorizontalAlignment', 'center');
pause
%% slide ad block
patch_slide(rect_ad, ...
[0, 0, 0, 0], [0, b, b, 0], t_pause=0.004)
draw_gridline(rect_ad, ["12", "34"])
pause
%% slide ad block
patch_slide(rect_ad, ...
[0, 0, d/(d/c-b/a), d/(d/c-b/a)],...
[0, 0, b/a*d/(d/c-b/a), b/a*d/(d/c-b/a)], t_pause=0.004)
draw_gridline(rect_ad, ["14", "23"])
pause
%% slide bc block
uistack(p_cd, 'top')
patch_slide(rect_bc, ...
[0, 0, 0, 0], [d, d, d, d], t_pause=0.004)
draw_gridline(rect_bc, "34")
pause
%% slide bc block
patch_slide(rect_bc, ...
[0, 0, a, a], [0, 0, 0, 0], t_pause=0.004)
draw_gridline(rect_bc, "23")
pause
%% slide bc block
patch_slide(rect_bc, ...
[d/(d/c-b/a), 0, 0, d/(d/c-b/a)], ...
[b/a*d/(d/c-b/a), 0, 0, b/a*d/(d/c-b/a)], t_pause=0.004)
pause
%% finalize: fade out ad, bc, and fade in ad-bc
rect_ad.UserData.Visible = 'off';
rect_bc.UserData.Visible = 'off';
fadeinout([rect_ad, rect_bc, area], [0, 0, 1])
area.UserData.String = 'ad-bc';
area.UserData.Visible = 'on';
%% functions
function fadeinout(objs, inout, options)
arguments
objs
inout % 1이면 fade-in, 0이면 fade-out
options.anim_Nsteps = 30
options.t_pause = 0.003
end
for alpha = linspace(0, 1, options.anim_Nsteps)
for i = 1:length(objs)
switch objs(i).Type
case 'patch'
objs(i).FaceAlpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
objs(i).EdgeAlpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
case 'constantline'
objs(i).Alpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
end
pause(options.t_pause)
end
end
end
function patch_slide(obj, x_dist, y_dist, options)
arguments
obj
x_dist
y_dist
options.anim_Nsteps = 30
options.t_pause = 0.003
end
dx = x_dist/options.anim_Nsteps;
dy = y_dist/options.anim_Nsteps;
for i=1:options.anim_Nsteps
obj.XData = obj.XData + dx(:);
obj.YData = obj.YData + dy(:);
obj.UserData.Position(1) = mean(obj.XData);
obj.UserData.Position(2) = mean(obj.YData);
pause(options.t_pause)
end
end
function draw_gridline(patch, where)
ax = patch.Parent;
for i=1:length(where)
v1 = str2double(where{i}(1));
v2 = str2double(where{i}(2));
x1 = patch.XData(v1);
x2 = patch.XData(v2);
y1 = patch.YData(v1);
y2 = patch.YData(v2);
if x1==x2
xline(x1, 'k--')
else
fplot(@(x) (y2-y1)/(x2-x1)*(x-x1)+y1, [ax.XLim(1), ax.XLim(2)], 'k--')
end
end
end