搜索



t = turtle(); % Start a turtle
t.forward(100); % Move forward by 100
t.backward(100); % Move backward by 100
t.left(90); % Turn left by 90 degrees
t.right(90); % Tur right by 90 degrees
t.goto(100, 100); % Move to (100, 100)
t.turnto(90); % Turn to 90 degrees, i.e. north
t.speed(1000); % Set turtle speed as 1000 (default: 500)
t.pen_up(); % Pen up. Turtle leaves no trace.
t.pen_down(); % Pen down. Turtle leaves a trace again.
t.color('b'); % Change line color to 'b'
t.begin_fill(FaceColor, EdgeColor, FaceAlpha); % Start filling
t.end_fill(); % End filling
t.change_icon('person.png'); % Change the icon to 'person.png'
t.clear(); % Clear the Axes
classdef turtle < handle
properties (GetAccess = public, SetAccess = private)
x = 0
y = 0
q = 0
end
properties (SetAccess = public)
speed (1, 1) double = 500
end
properties (GetAccess = private)
speed_reg = 100
n_steps = 20
ax
l
ht
im
is_pen_up = false
is_filling = false
fill_color
fill_alpha
end
methods
function obj = turtle()
figure(Name='MATurtle', NumberTitle='off')
obj.ax = axes(box="on");
hold on,
obj.ht = hgtransform();
icon = flipud(imread('turtle.png'));
obj.im = imagesc(obj.ht, icon, ...
XData=[-30, 30], YData=[-30, 30], ...
AlphaData=(255 - double(rgb2gray(icon)))/255);
obj.l = plot(obj.x, obj.y, 'k');
obj.ax.XLim = [-500, 500];
obj.ax.YLim = [-500, 500];
obj.ax.DataAspectRatio = [1, 1, 1];
obj.ax.Toolbar.Visible = 'off';
disableDefaultInteractivity(obj.ax);
end
function home(obj)
obj.x = 0;
obj.y = 0;
obj.ht.Matrix = eye(4);
end
function forward(obj, dist)
obj.step(dist);
end
function backward(obj, dist)
obj.step(-dist)
end
function step(obj, delta)
if numel(delta) == 1
delta = delta*[cosd(obj.q), sind(obj.q)];
end
if obj.is_filling
obj.fill(delta);
else
obj.move(delta);
end
end
function goto(obj, x, y)
dx = x - obj.x;
dy = y - obj.y;
obj.turnto(rad2deg(atan2(dy, dx)));
obj.step([dx, dy]);
end
function left(obj, q)
obj.turn(q);
end
function right(obj, q)
obj.turn(-q);
end
function turnto(obj, q)
obj.turn(obj.wrap_angle(q - obj.q, -180));
end
function pen_up(obj)
if obj.is_filling
warning('not available while filling')
return
end
obj.is_pen_up = true;
end
function pen_down(obj, go)
if obj.is_pen_up
if nargin == 1
obj.l(end+1) = plot(obj.x, obj.y, Color=obj.l(end).Color);
else
obj.l(end+1) = go;
end
uistack(obj.ht, 'top')
end
obj.is_pen_up = false;
end
function color(obj, line_color)
if obj.is_filling
warning('not available while filling')
return
end
obj.pen_up();
obj.pen_down(plot(obj.x, obj.y, Color=line_color));
end
function begin_fill(obj, FaceColor, EdgeColor, FaceAlpha)
arguments
obj
FaceColor = [.6, .9, .6];
EdgeColor = [0 0.4470 0.7410];
FaceAlpha = 1;
end
if obj.is_filling
warning('already filling')
return
end
obj.fill_color = FaceColor;
obj.fill_alpha = FaceAlpha;
obj.pen_up();
obj.pen_down(patch(obj.x, obj.y, [1, 1, 1], ...
EdgeColor=EdgeColor, FaceAlpha=0));
obj.is_filling = true;
end
function end_fill(obj)
if ~obj.is_filling
warning('not filling now')
return
end
obj.l(end).FaceColor = obj.fill_color;
obj.l(end).FaceAlpha = obj.fill_alpha;
obj.is_filling = false;
end
function change_icon(obj, filename)
icon = flipud(imread(filename));
obj.im.CData = icon;
obj.im.AlphaData = (255 - double(rgb2gray(icon)))/255;
end
function clear(obj)
obj.x = 0;
obj.y = 0;
delete(obj.ax.Children(2:end));
obj.l = plot(0, 0, 'k');
obj.ht.Matrix = eye(4);
end
end
methods (Access = private)
function animated_step(obj, delta, q, initFcn, updateFcn)
arguments
obj
delta
q
initFcn = @() []
updateFcn = @(~, ~) []
end
dx = delta(1)/obj.n_steps;
dy = delta(2)/obj.n_steps;
dq = q/obj.n_steps;
pause_duration = norm(delta)/obj.speed/obj.speed_reg;
initFcn();
for i = 1:obj.n_steps
updateFcn(dx, dy);
obj.ht.Matrix = makehgtform(...
translate=[obj.x + dx*i, obj.y + dy*i, 0], ...
zrotate=deg2rad(obj.q + dq*i));
pause(pause_duration)
drawnow limitrate
end
obj.x = obj.x + delta(1);
obj.y = obj.y + delta(2);
end
function obj = turn(obj, q)
obj.animated_step([0, 0], q);
obj.q = obj.wrap_angle(obj.q + q, 0);
end
function move(obj, delta)
initFcn = @() [];
updateFcn = @(dx, dy) [];
if ~obj.is_pen_up
initFcn = @() initializeLine();
updateFcn = @(dx, dy) obj.update_end_point(obj.l(end), dx, dy);
end
function initializeLine()
obj.l(end).XData(end+1) = obj.l(end).XData(end);
obj.l(end).YData(end+1) = obj.l(end).YData(end);
end
obj.animated_step(delta, 0, initFcn, updateFcn);
end
function obj = fill(obj, delta)
initFcn = @() initializePatch();
updateFcn = @(dx, dy) obj.update_end_point(obj.l(end), dx, dy);
function initializePatch()
obj.l(end).Vertices(end+1, :) = obj.l(end).Vertices(end, :);
obj.l(end).Faces = 1:size(obj.l(end).Vertices, 1);
end
obj.animated_step(delta, 0, initFcn, updateFcn);
end
end
methods (Static, Access = private)
function update_end_point(l, dx, dy)
l.XData(end) = l.XData(end) + dx;
l.YData(end) = l.YData(end) + dy;
end
function q = wrap_angle(q, min_angle)
q = mod(q - min_angle, 360) + min_angle;
end
end
end
Nice to have - function output argument provide code assist when said function is called
This is a feature which doesn't apear to currently exist, but I think alot of matlab users would like, particularly ones who write alot of custom classes.
Imagine i have a custom class with some properties:
classdef CustomClass < handle
properties
name (1,1) string = "default name"
varOne (1,1) double = 0
end
methods
function obj = CustomClass(name,varOne)
obj.name = name;
obj.VarOne = varOne;
end
end
end
Then imagine I have a function which returns one of these custom class objects:
function [obj] = Calculation(Var1,Var2,name)
arguments (Input)
Var1 (1,1) double
Var2 (1,1) double
end
arguments (Output)
obj (1,1) CustomClass
end
results = Var1 + Var2;
obj = CustomClass(name,result);
end
With this class and this function which returns one of these class objects, I would like the fact that I provided "(1,1) CustomClass" in the output arguemnts block of function "Calculation(Var1,Var2,name)" to trigger code assist automaticaly show me, when writing code that the retuned value from this funciton has properties "name" and "varOne" in the object.
For istance, if I write the following code with this function and the class in the Matlab search path
testObj = Calculation(1,1,"test");
testObj.varOne = 10; %the property "varOne" doesn't apear in code assist when writing this line of code
I would like that the fact function "Calcuation(Var1,Var2,name) has the output arguments block enforcing that this function must return an object of "CustomClass" to make code assist recognise that "testObj" is a "CustomClass" object, just as if testObj was an input argument to another function which had an input argument requiring that "testObj" was a "CustomClass" object.
Maybe this is a feature that may be added to matlab in future releases? (please and thank you LOL)
This is a feature which doesn't apear to currently exist, but I think alot of matlab users would like, particularly ones who write alot of custom classes.
Imagine i have a custom class with some properties:
classdef CustomClass < handle
properties
name (1,1) string = "default name"
varOne (1,1) double = 0
end
methods
function obj = CustomClass(name,varOne)
obj.name = name;
obj.VarOne = varOne;
end
end
end
Then imagine I have a function which returns one of these custom class objects:
function [obj] = Calculation(Var1,Var2,name)
arguments (Input)
Var1 (1,1) double
Var2 (1,1) double
end
arguments (Output)
obj (1,1) CustomClass
end
results = Var1 + Var2;
obj = CustomClass(name,result);
end
With this class and this function which returns one of these class objects, I would like the fact that I provided "(1,1) CustomClass" in the output arguemnts block of function "Calculation(Var1,Var2,name)" to trigger code assist automaticaly show me, when writing code that the retuned value from this funciton has properties "name" and "varOne" in the object.
For istance, if I write the following code with this function and the class in the Matlab search path
testObj = Calculation(1,1,"test");
testObj.varOne = 10; %the property "varOne" doesn't apear in code assist when writing this line of code
I would like that the fact function "Calcuation(Var1,Var2,name) has the output arguments block enforcing that this function must return an object of "CustomClass" to make code assist recognise that "testObj" is a "CustomClass" object, just as if testObj was an input argument to another function which had an input argument requiring that "testObj" was a "CustomClass" object.
Maybe this is a feature that may be added to matlab in future releases? (please and thank you LOL)
I would like to zoom directly on the selected region when using
on my image created with image or imagesc. First of all, I would recommend using image or imagesc and not imshow for this case, see comparison here: Differences between imshow() and image()? However when zooming Stretch-to-Fill behavior happens and I don't want that. Try range zoom to image generated by this code:

fig = uifigure;
ax = uiaxes(fig);
im = imread("peppers.png");
h = imagesc(im,"Parent",ax);
axis(ax,'tight', 'off')
I can fix that with manualy setting data aspect ratio:
daspect(ax,[1 1 1])
However, I need this code to run automatically after zooming. So I create zoom object and ActionPostCallback which is called everytime after I zoom, see zoom - ActionPostCallback.
z = zoom(ax);
z.ActionPostCallback = @(fig,ax) daspect(ax.Axes,[1 1 1]);
If you need, you can also create ActionPreCallback which is called everytime before I zoom, see zoom - ActionPreCallback.
z.ActionPreCallback = @(fig,ax) daspect(ax.Axes,'auto');
Code written and run in R2025a.
I am thrilled python interoperability now seems to work for me with my APPLE M1 MacBookPro and MATLAB V2025a. The available instructions are still, shall we say, cryptic. Here is a summary of my interaction with GPT 4o to get this to work.
===========================================================
MATLAB R2025a + Python (Astropy) Integration on Apple Silicon (M1/M2/M3 Macs)
===========================================================
Author: D. Carlsmith, documented with ChatGPT
Last updated: July 2025
This guide provides full instructions, gotchas, and workarounds to run Python 3.10 with MATLAB R2025a (Apple Silicon/macOS) using native ARM64 Python and calling modules like Astropy, Numpy, etc. from within MATLAB.
===========================================================
Overview
===========================================================
- MATLAB R2025a on Apple Silicon (M1/M2/M3) runs as "maca64" (native ARM64).
- To call Python from MATLAB, the Python interpreter must match that architecture (ARM64).
- Using Intel Python (x86_64) with native MATLAB WILL NOT WORK.
- The cleanest solution: use Miniforge3 (Conda-forge's lightweight ARM64 distribution).
===========================================================
1. Install Miniforge3 (ARM64-native Conda)
===========================================================
In Terminal, run:
curl -LO https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
bash Miniforge3-MacOSX-arm64.sh
Follow prompts:
- Press ENTER to scroll through license.
- Type "yes" when asked to accept the license.
- Press ENTER to accept the default install location: ~/miniforge3
- When asked:
Do you wish to update your shell profile to automatically initialize conda? [yes|no]
Type: yes
===========================================================
2. Restart Terminal and Create a Python Environment for MATLAB
===========================================================
Run the following:
conda create -n matlab python=3.10 astropy numpy -y
conda activate matlab
Verify the Python path:
which python
Expected output:
/Users/YOURNAME/miniforge3/envs/matlab/bin/python
===========================================================
3. Verify Python + Astropy From Terminal
===========================================================
Run:
python -c "import astropy; print(astropy.__version__)"
Expected output:
6.x.x (or similar)
===========================================================
4. Configure MATLAB to Use This Python
===========================================================
In MATLAB R2025a (Apple Silicon):
clear classes
pyenv('Version', '/Users/YOURNAME/miniforge3/envs/matlab/bin/python')
py.sys.version
You should see the Python version printed (e.g. 3.10.18). No error means it's working.
===========================================================
5. Gotchas and Their Solutions
===========================================================
❌ Error: Python API functions are not available
→ Cause: Wrong architecture or broken .dylib
→ Fix: Use Miniforge ARM64 Python. DO NOT use Intel Anaconda.
❌ Error: Invalid text character (↑ points at __version__)
→ Cause: MATLAB can’t parse double underscores typed or pasted
→ Fix: Use: py.getattr(module, '__version__')
❌ Error: Unrecognized method 'separation' or 'sec'
→ Cause: MATLAB can't reflect dynamic Python methods
→ Fix: Use: py.getattr(obj, 'method')(args)
===========================================================
6. Run Full Verification in MATLAB
===========================================================
Paste this into MATLAB:
% Set environment
clear classes
pyenv('Version', '/Users/YOURNAME/miniforge3/envs/matlab/bin/python');
% Import modules
coords = py.importlib.import_module('astropy.coordinates');
time_mod = py.importlib.import_module('astropy.time');
table_mod = py.importlib.import_module('astropy.table');
% Astropy version
ver = char(py.getattr(py.importlib.import_module('astropy'), '__version__'));
disp(['Astropy version: ', ver]);
% SkyCoord angular separation
c1 = coords.SkyCoord('10h21m00s', '+41d12m00s', pyargs('frame', 'icrs'));
c2 = coords.SkyCoord('10h22m00s', '+41d15m00s', pyargs('frame', 'icrs'));
sep_fn = py.getattr(c1, 'separation');
sep = sep_fn(c2);
arcsec = double(sep.to('arcsec').value);
fprintf('Angular separation = %.3f arcsec\n', arcsec);
% Time difference in seconds
Time = time_mod.Time;
t1 = Time('2025-01-01T00:00:00', pyargs('format','isot','scale','utc'));
t2 = Time('2025-01-02T00:00:00', pyargs('format','isot','scale','utc'));
dt = py.getattr(t2, '__sub__')(t1);
seconds = double(py.getattr(dt, 'sec'));
fprintf('Time difference = %.0f seconds\n', seconds);
% Astropy table display
tbl = table_mod.Table(pyargs('names', {'a','b'}, 'dtype', {'int','float'}));
tbl.add_row({1, 2.5});
tbl.add_row({2, 3.7});
disp(tbl);
===========================================================
7. Optional: Automatically Configure Python in startup.m
===========================================================
To avoid calling pyenv() every time, edit your MATLAB startup:
edit startup.m
Add:
try
pyenv('Version', '/Users/YOURNAME/miniforge3/envs/matlab/bin/python');
catch
warning("Python already loaded.");
end
===========================================================
8. Final Notes
===========================================================
- This setup avoids all architecture mismatches.
- It uses a clean, minimal ARM64 Python that integrates seamlessly with MATLAB.
- Do not mix Anaconda (Intel) with Apple Silicon MATLAB.
- Use py.getattr for any Python attribute containing underscores or that MATLAB can't resolve.
You can now run NumPy, Astropy, Pandas, Astroquery, Matplotlib, and more directly from MATLAB.
===========================================================
群馬産業技術センター様をお招きし、製造現場での異常検知の取り組みについてご紹介いただくオンラインセミナーを開催します。
実際の開発事例を通して、MATLABを使った「教師なし」異常検知の進め方や、予知保全に役立つ最新機能もご紹介します。
✅ 異常検知・予知保全に興味がある方
✅ データ活用を何から始めればいいか迷っている方
✅ 実際の現場事例を知りたい方
ぜひお気軽にご参加ください!

Hey MATLAB enthusiasts!
I just stumbled upon this hilariously effective GitHub repo for image deformation using Moving Least Squares (MLS)—and it’s pure gold for anyone who loves playing with pixels! 🎨✨
- Real-Time Magic ✨
- Precomputes weights and deformation data upfront, making it blazing fast for interactive edits. Drag control points and watch the image warp like rubber! (2)
- Supports affine, similarity, and rigid deformations—because why settle for one flavor of chaos?
- Single-File Simplicity 🧩
- All packed into one clean MATLAB class (mlsImageWarp.m).
- Endless Fun Use Cases 🤹
- Turn your pet’s photo into a Picasso painting.
- "Fix" your friend’s smile... aggressively.
- Animate static images with silly deformations (1).
Try the Demo!
Hi everyone,
Please check out our new book "Generative AI for Trading and Asset Management".
GenAI is usually associated with large language models (LLMs) like ChatGPT, or with image generation tools like MidJourney, essentially, machines that can learn from text or images and generate text or images. But in reality, these models can learn from many different types of data. In particular, they can learn from time series of asset returns, which is perhaps the most relevant for asset managers.
In our book (amazon.com link), we explore both the practical applications and the fundamental principles of GenAI, with a special focus on how these technologies apply to trading and asset management.
The book is divided into two broad parts:
Part 1 is written by Ernie Chan, noted author of Quantitative Trading, Algorithmic Trading, and Machine Trading. It starts with no-code applications of GenAI for traders and asset managers with little or no coding experience. After that, it takes readers on a whirlwind tour of machine learning techniques commonly used in finance.
Part 2, written by Hamlet, covers the fundamentals and technical details of GenAI, from modeling to efficient inference. This part is for those who want to understand the inner workings of these models and how to adapt them to their own custom data and applications. It’s for anyone who wants to go beyond the high-level use cases, get their hands dirty, and apply, and eventually improve these models in real-world practical applications.
Readers can start with whichever part they want to explore and learn from.
You are not a jedi yet !
20%
We not grant u the rank of master !
0%
Ready are u? What knows u of ready?
0%
May the Force be with you !
80%
5 个投票
Simulinkモデルを生成AIで自動的に作成できたら便利だと思いませんか?
QiitaのSacredTubesさんは、このアイデアを実験的に試みた記事を公開しています。
その方法は、まず生成AIでVerilogコードを作成し、それをSimulinkに取り込んでモデル化するというものです。(ここではHDL Coderというツールボックスの機能が使われました:importhdl)
まだ実用段階には至っていませんが、モデルベース開発(MBD)と生成AIの可能性を探る上で、非常に興味深い試みです。
生成AIの限界と可能性を考えるきっかけとして、一読の価値があります。
---
もし「Simulink Copilot」のような生成AIツールが登場するとしたら、
どんな機能があったら嬉しいと思いますか?
- 自然言語でブロック図を生成?
- 既存モデルの自動ドキュメント化?
- シミュレーション結果の要約と解釈?
皆さんのアイデアをぜひシェアしてください!
- 昨日までちゃんと動いていたのに・・
- ヘルプページ通りに書いているのに・・
MATLAB 関数がエラーを出すようになることありますよね(?)そんな時にみなさんがまず確認するもの、何かありますか?教えてください!
例えば
which -all plot
をコマンドウィンドウで実行して、もともと MATLAB で定義されている plot 関数(MATLAB のインストールフォルダにある plot 関数)がちゃんと頭に出てくるかどうか確認します。
I am deeply honored to announce the official publication of my latest academic volume:
MATLAB for Civil Engineers: From Basics to Advanced Applications
(Springer Nature, 2025).
This work serves as a comprehensive bridge between theoretical civil engineering principles and their practical implementation through MATLAB—a platform essential to the future of computational design, simulation, and optimization in our field.
Structured to serve both academic audiences and practicing engineers, this book progresses from foundational MATLAB programming concepts to highly specialized applications in structural analysis, geotechnical engineering, hydraulic modeling, and finite element methods. Whether you are a student building analytical fluency or a professional seeking computational precision, this volume offers an indispensable resource for mastering MATLAB's full potential in civil engineering contexts.
With rigorously structured examples, case studies, and research-aligned methods, MATLAB for Civil Engineers reflects the convergence of engineering logic with algorithmic innovation—equipping readers to address contemporary challenges with clarity, accuracy, and foresight.
📖 Ideal for:
— Graduate and postgraduate civil engineering students
— University instructors and lecturers seeking a structured teaching companion
— Professionals aiming to integrate MATLAB into complex real-world projects
If you are passionate about engineering resilience, data-informed design, or computational modeling, I invite you to explore the work and share it with your network.
🧠 Let us advance the discipline together through precision, programming, and purpose.

Untapped Potential for Output-arguments Block
MATLAB has a very powerful feature in its arguments blocks. For example, the following code for a function (or method):
- clearly outlines all the possible inputs
- provides default values for each input
- will produce auto-complete suggestions while typing in the Editor (and Command Window in newer versions)
- checks each input against validation functions to enforce size, shape (e.g., column vs. row vector), type, and other options (e.g., being a member of a set)
function [out] = sample_fcn(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
% function logic ...
end
If you do not already use the arguments block for function (or method) inputs, I strongly suggest that you try it out.
The point of this post, though, is to suggest improvements for the output-arguments block, as it is not nearly as powerful as its input-arguments counterpart. I have included two function examples: the first can work in MATLAB while the second does not, as it includes suggestions for improvements. Commentary specific to each function is provided completely before the code. While this does necessitate navigating back and forth between functions and text, this provides for an easy comparison between the two functions which is my main goal.
Current Implementation
The input-arguments block for sample_fcn begins the function and has already been discussed. A simple output-arguments block is also included. I like to use a single output so that additional fields may be added at a later point. Using this approach simplifies future development, as the function signature, wherever it may be used, does not need to be changed. I can simply add another output field within the function and refer to that additional field wherever the function output is used.
Before beginning any logic, sample_fcn first assigns default values to four fields of out. This is a simple and concise way to ensure that the function will not error when returning early.
The function then performs two checks. The first is for an empty input (x) vector. If that is the case, nothing needs to be done, as the function simply returns early with the default output values that happen to apply to the inability to fit any data.
The second check is for edge cases for which input combinations do not work. In this case, the status is updated, but default values for all other output fields (which are already assigned) still apply, so no additional code is needed.
Then, the function performs the fit based on the specified model_type. Note that an otherwise case is not needed here, since the argument validation for model_type would not allow any other value.
At this point, the total_error is calculated and a check is then made to determine if it is valid. If not, the function again returns early with another specific status value.
Finally, the R^2 value is calculated and a fourth check is performed. If this one fails, another status value is assigned with an early return.
If the function has passed all the checks, then a set of assertions ensure that each of the output fields are valid. In this case, there are eight specific checks, two for each field.
If all of the assertions also pass, then the final (successful) status is assigned and the function returns normally.
function [out] = sample_fcn(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
arguments(Output)
out struct
end
%%
out.fit = [];
out.total_error = [];
out.R_squared = NaN;
out.status = "Fit not possible for supplied inputs.";
%%
if isempty(in.x)
return
end
%%
if ((in.model_type == "2-factor") && (in.number_of_terms == 5)) || ... % other possible logic
out.status = "Specified combination of model_type and number_of_terms is not supported.";
return
end
%%
switch in.model_type
case "2-factor"
out.fit = % code for 2-factor fit
case "3-factor"
out.fit = % code for 3-factor fit
case "4-factor"
out.fit = % code for 4-factor fit
end
%%
out.total_error = % calculation of error
if ~isfinite(out.total_error)
out.status = "The total_error could not be calculated.";
return
end
%%
out.R_squared = % calculation of R^2
if out.R_squared > 1
out.status = "The R^2 value is out of bounds.";
return
end
%%
assert(iscolumn(out.fit), "The fit vector is not a column vector.");
assert(size(out.fit) == size(in.x), "The fit vector is not the same size as the input x vector.");
assert(isscalar(out.total_error), "The total_error is not a scalar.");
assert(isfinite(out.total_error), "The total_error is not finite.");
assert(isscalar(out.R_squared), "The R^2 value is not a scalar.");
assert(isfinite(out.R_squared), "The R^2 value is not finite.");
assert(isscalar(out.status), "The status is not a scalar.");
assert(isstring(out.status), "The status is not a string.");
%%
out.status = "The fit was successful.";
end
Potential Implementation
The second function, sample_fcn_output_arguments, provides essentially the same functionality in about half the lines of code. It is also much clearer with respect to the output. As a reminder, this function structure does not currently work in MATLAB, but hopefully it will in the not-too-distant future.
This function uses the same input-arguments block, which is then followed by a comparable output-arguments block. The first unsupported feature here is the use of name-value pairs for outputs. I would much prefer to make these assignments here rather than immediately after the block as in the sample_fcn above, which necessitates four more lines of code.
The mustBeSameSize validation function that I use for fit does not exist, but I really think it should; I would use it a lot. In this case, it provides a very succinct way of ensuring that the function logic did not alter the size of the fit vector from what is expected.
The mustBeFinite validation function for out.total_error does not work here simply because of the limitation on name-value pairs; it does work for regular outputs.
Finally, the assignment of default values to output arguments is not supported.
The next three sections of sample_fcn_output_arguments match those of sample_fcn: check if x is empty, check input combinations, and perform fit logic. Following that, though, the functions diverge heavily, as you might expect. The two checks for total_error and R^2 are not necessary, as those are covered by the output-arguments block. While there is a slight difference, in that the specific status values I assigned in sample_fcn are not possible, I would much prefer to localize all these checks in the arguments block, as is already done for input arguments.
Furthermore, the entire section of eight assertions in sample_fcn is removed, as, again, that would be covered by the output-arguments block.
This function ends with the same status assignment. Again, this is not exactly the same as in sample_fcn, since any failed assertion would prevent that assignment. However, that would also halt execution, so it is a moot point.
function [out] = sample_fcn_output_arguments(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
arguments(Output)
out.fit (:, 1) {mustBeSameSize(out.fit, in.x)} = []
out.total_error (1, 1) {mustBeFinite(out.total_error)} = []
out.R_squared (1, 1) {mustBeLessThanOrEqual(out.R_squared, 1)} = NaN
out.status (1, 1) string = "Fit not possible for supplied inputs."
end
%%
if isempty(in.x)
return
end
%%
if ((in.model_type == "2-factor") && (in.number_of_terms == 5)) || ... % other possible logic
out.status = "Specified combination of model_type and number_of_terms is not supported.";
return
end
%%
switch in.model_type
case "2-factor"
out.fit = % code for 2-factor fit
case "3-factor"
out.fit = % code for 3-factor fit
case "4-factor"
out.fit = % code for 4-factor fit
end
%%
out.status = "The fit was successful.";
end
Final Thoughts
There is a significant amount of unrealized potential for the output-arguments block. Hopefully what I have provided is helpful for continued developments in this area.
What are your thoughts? How would you improve arguments blocks for outputs (or inputs)? If you do not already use them, I hope that you start to now.
キーと値の組み合わせでデータを格納できるディクショナリ。R2022bでdictionaryコマンドが登場し、最近のバージョンではreaddictionaryとwritedictionaryでJSONファイルからの読み込み・書き込みにも対応しました。
私はMIDIデータからピアノの演奏動画を作るプログラムで、ディクショナリを使いました。音のノート番号をキーにして、patchで白と黒で鍵盤を塗りつぶしたmatlab.graphics.Graphicsデータ型を値にしたディクショナリで保存して、MIDIで鳴らされた音のノート番号からlookupでグラフのオブジェクトを取得し、FaceColorを変更してハイライトするというもの。

コード例
%% MIDIデータの.matファイルを読み取ってピアノを描画するサンプル
fig = figure('Position', [34 328 1626 524]);
ax = axes;
whiteKeyY = [0 0 150 150];
whiteKeyColor = [1 1 1];
blackKeyY = [50 50 150 150];
blackKeyColor = [0.1 0.1 0.1];
edgeColor = [0 0 0];
% ディクショナリの定義
d = configureDictionary("double", "matlab.graphics.Graphics");
% 白鍵を描画
for n = 1:9
pos = 23*7*(n-1);
d = insert(d, 21 + (n-1)*12, patch([pos+5 pos+28 pos+28 pos+5],whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 21 + (n-1)*12));
d = insert(d, 23 + (n-1)*12, patch([pos+28 pos+51 pos+51 pos+28], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 23 + (n-1)*12));
d = insert(d, 24 + (n-1)*12, patch([pos+51 pos+74 pos+74 pos+51], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 24 + (n-1)*12));
if n < 9
d = insert(d, 26 + (n-1)*12, patch([pos+74 pos+97 pos+97 pos+74], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 26 + (n-1)*12));
d = insert(d, 28 + (n-1)*12, patch([pos+97 pos+120 pos+120 pos+97], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 28 + (n-1)*12));
d = insert(d, 29 + (n-1)*12, patch([pos+120 pos+143 pos+143 pos+120], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 29 + (n-1)*12));
d = insert(d, 31 + (n-1)*12, patch([pos+143 pos+166 pos+166 pos+143], whiteKeyY, whiteKeyColor, 'EdgeColor', edgeColor, 'UserData', 31 + (n-1)*12));
end
end
% 黒鍵を描画。白鍵の上になるようにループを分けています
for n = 1:9
pos = 23*7*(n-1);
d = insert(d, 22 + (n-1)*12, patch([pos+23 pos+33 pos+33 pos+23], blackKeyY, blackKeyColor, 'EdgeColor', [0 0 0], 'UserData', 22 + (n-1)*12));
if n < 9
d = insert(d, 25 + (n-1)*12, patch([pos+69 pos+79 pos+79 pos+69], blackKeyY, blackKeyColor, 'EdgeColor', [0 0 0], 'UserData', 25 + (n-1)*12));
d = insert(d, 27 + (n-1)*12, patch([pos+92 pos+102 pos+102 pos+92], blackKeyY, blackKeyColor, 'EdgeColor', [0 0 0], 'UserData', 27 + (n-1)*12));
d = insert(d, 30 + (n-1)*12, patch([pos+138 pos+148 pos+148 pos+138], blackKeyY, blackKeyColor, 'EdgeColor', [0 0 0], 'UserData', 30 + (n-1)*12));
d = insert(d, 32 + (n-1)*12, patch([pos+161 pos+171 pos+171 pos+161], blackKeyY, blackKeyColor, 'EdgeColor', [0 0 0], 'UserData', 32 + (n-1)*12));
end
end
xticklabels({})
yticklabels({})
xlim([5 1362])
drawnow
%% MIDI音源の.matファイルを読み込み
matData = load('fur-elise.mat');
msg = matData.receivedMessages;
eventTimes = [msg.Timestamp] - msg(1).Timestamp;
n = 1;
numNotes = 0;
lastNote = 0;
highlightedCircles = cell(1, 127);
% 音が鳴った鍵盤だけハイライトする
tic
while toc < max(eventTimes)
if toc > eventTimes(n)
thisMsg = msg(n);
if thisMsg.Type == "NoteOn"
numNotes = numNotes + 1;
lastNote = thisMsg.Note;
thisPatch = lookup(d, thisMsg.Note);
thisPatch.FaceColor = '#CCFFCC';
drawnow
elseif thisMsg.Type == "NoteOff"
numNotes = 0;
thisPatch = lookup(d, thisMsg.Note);
[~, ~, wOrB] = calcNotePos(thisMsg.Note);
if wOrB == "w"
thisPatch.FaceColor = 'white';
else
thisPatch.FaceColor = 'black';
end
drawnow
end
n = n+1;
end
end
%% サブ関数
function [pianoPos, centerPos, wOrB] = calcNotePos(note)
tempVar = idivide(int64(note), int64(12)); % 12で割った商
pos = 23*7*(tempVar-1);
switch mod(note, 12)
case 0 % C
pianoPos = pos + 62.5;
centerPos = 30;
wOrB = "w";
case 2 % D
pianoPos = pos + 85.5;
centerPos = 30;
wOrB = "w";
case 4 % E
pianoPos = pos + 108.5;
centerPos = 30;
wOrB = "w";
case 5 % F
pianoPos = pos + 131.5;
centerPos = 30;
wOrB = "w";
case 7 % G
pianoPos = pos + 154.5;
centerPos = 30;
wOrB = "w";
case 9 % A
pianoPos = pos + 177.5;
centerPos = 30;
wOrB = "w";
case 11 % B
pianoPos = pos + 200.5;
centerPos = 30;
wOrB = "w";
case 1 % C#
pianoPos = pos + 69;
centerPos = 100;
wOrB = "b";
case 3 % D#
pianoPos = pos + 92;
centerPos = 100;
wOrB = "b";
case 6 % F#
pianoPos = pos + 138;
centerPos = 100;
wOrB = "b";
case 8 % G#
pianoPos = pos + 161;
centerPos = 100;
wOrB = "b";
case 10 % A#
pianoPos = pos + 184;
centerPos = 100;
wOrB = "b";
end
end
皆さんはディクショナリを使ってますか? もし使っていたら、どういう活用をしているか、聞かせてください!
どの方法を使う事が多いですか?他によく使う方法があれば教えてくださいー。
方法①
Livescript 上で for ループ内で描画を編集させて描いた動画は「アニメーションのエクスポート」から動画ファイルに出力するのが一番簡単ですね。再生速度やら細かい設定ができない点は要注意。

方法②
exportgraphics 関数で "Append" オプション指定で実現できるようになった(R2022a から)のでこれも便利ですね。
N = 100;
x = linspace(0,4*pi,N);
y = sin(x);
filename = 'animation_sample.gif'; % Specify the output file name
if exist(filename,'file')
delete(filename)
end
h = animatedline;
axis([0,4*pi,-1,1]) % x軸の表示範囲を固定
for k = 1:length(x)
addpoints(h,x(k),y(k)); % ループでデータを追加
exportgraphics(gca,filename,"Append",true)
end
方法③
R2021b 以前のバージョンだとこんな感じ。
各ループで画面キャプチャして、imwrite で動画ファイルにフレーム追加していくイメージです。"DelayTime" を使って細かい指定ができるので、必要に応じて今でも利用します。
for k = 1:length(x)
addpoints(h,x(k),y(k)); % ループでデータを追加
drawnow % グラフアップデート
frame = getframe(gcf); % Figure 画面をムービーフレーム(構造体)としてキャプチャ
tmp = frame2im(frame); % 画像に変更
[A,map] = rgb2ind(tmp,256); % RGB -> インデックス画像に
if k == 1 % 新規 gif ファイル作成
imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',0.2);
else % 以降、画像をアペンド
imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',0.2);
end
end
I saw this on Reddit and thought of the past mini-hack contests. We have a few folks here who can do something similar with MATLAB.
これからは生成AIでコードを1から書くという事が減ってくるのかと思いますが,皆さんがMATLABのコードを書く時に意識しているご自身のルールのようなものがあれば教えてください.
MATLAB言語は柔軟に書けますが,自然と個人個人のルールというものが出来上がってきているのでは,と思います.
私はParameter, Valueペアの引数がある関数はそれぞれのペアを新しい行に書く,というのをよくやります.
h = plot(x, y, "ro-", ...
"LineWidth", 2, ...
"MarkerSize", 10, ...
"MarkerFaceColor", "g");
Parameter=Valueでも同じです.
h = plot(x, y, "ro-", ...
LineWidth = 2, ...
MarkerSize = 10, ...
MarkerFaceColor = "g");
また,一時期は "=" を揃えることもやってました(今はやってませんが).
h = plot(x, y, "ro-", ...
LineWidth = 2, ...
MarkerSize = 10, ...
MarkerFaceColor = "g");
皆さんにはどのようなルールがありますか?
The Graphics and App Building Blog just launched its first article on R2025a features, authored by Chris Portal, the director of engineering for the MATLAB graphics and app building teams.
Over the next few months, we'll publish a series of articles that showcase our updated graphics system, introduce new tools and features, and provide valuable references enriched by the perspectives of those involved in their development.
To stay updated, you can subscribe to the blog (look for the option in the upper left corner of the blog page). We also encourage you to join the conversation—your comments and questions under each article help shape the discussion and guide future content.

I had an error in the web version Matlab, so I exited and came back in, and this boy was plotted.