メインコンテンツ

結果:

lazymatlab
lazymatlab
最後のアクティビティ: 約4時間 前

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
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を使った「教師なし」異常検知の進め方や、予知保全に役立つ最新機能もご紹介します。
✅ 異常検知・予知保全に興味がある方
✅ データ活用を何から始めればいいか迷っている方
✅ 実際の現場事例を知りたい方
ぜひお気軽にご参加ください!
Simulinkモデルを生成AIで自動的に作成できたら便利だと思いませんか?
QiitaのSacredTubesさんは、このアイデアを実験的に試みた記事を公開しています。
その方法は、まず生成AIでVerilogコードを作成し、それをSimulinkに取り込んでモデル化するというものです。(ここではHDL Coderというツールボックスの機能が使われました:importhdl
まだ実用段階には至っていませんが、モデルベース開発(MBD)と生成AIの可能性を探る上で、非常に興味深い試みです。
生成AIの限界と可能性を考えるきっかけとして、一読の価値があります。
---
もし「Simulink Copilot」のような生成AIツールが登場するとしたら、
どんな機能があったら嬉しいと思いますか?
  • 自然言語でブロック図を生成?
  • 既存モデルの自動ドキュメント化?
  • シミュレーション結果の要約と解釈?
皆さんのアイデアをぜひシェアしてください!
Jiro Doke
Jiro Doke
最後のアクティビティ: 2025 年 7 月 3 日 14:31

毎回 MATLAB を立ち上げたときに実行される startup,閉じるときに実行される finish って使ってますか?
久々に startup.m を開いてみたら
format short
format compact
disp("Ready")
の3行がありました.何らかの理由で format 設定を変えたとしても次回起動したときにはお気に入りの format に戻っているというのは嬉しいですよね!
disp("Ready")
は特に意味はありませんが,表示されると「さあ,始めよう!」って気分になります.(笑)
  • 昨日までちゃんと動いていたのに・・
  • ヘルプページ通りに書いているのに・・
MATLAB 関数がエラーを出すようになることありますよね(?)そんな時にみなさんがまず確認するもの、何かありますか?教えてください!
自分がまず試すのはこれ:which 。うっかり同じ名前の関数や変数を作っちゃっているかどうかを確認できます。
例えば
which -all plot
をコマンドウィンドウで実行して、もともと MATLAB で定義されている plot 関数(MATLAB のインストールフォルダにある plot 関数)がちゃんと頭に出てくるかどうか確認します。
キーと値の組み合わせでデータを格納できるディクショナリ。R2022bdictionaryコマンドが登場し、最近のバージョンではreaddictionarywritedictionaryJSONファイルからの読み込み・書き込みにも対応しました。
私は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 から)のでこれも便利ですね。
下の例では、ループで新規データを追加してアニメーションを作成するのに Animatedlineオブジェクト を使い、データの追加には addpoints を使用。
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
これからは生成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");
皆さんにはどのようなルールがありますか?
先日も X にポストしましたが、これ Ctrl + A, Ctrl + I
コードを書き加えながら定期的に手癖で Ctrl + A, Ctrl + I。for ループ書き直しているときなどインデント乱れがちですのでよく使います。
「これは、昨日知りたかったやつ。。便利!」(X
「めっちゃ使ってるこれ会社の人に教えたら「今までスペースキーで頑張ってたのはいったい…」て膝から崩れ落ちるような感じになってた」(X
そんな声がありました。
普段使っているショートカットキーも他の人にとっては未知なものかも。ここで共有してコード書きの効率あげていきましょう!
michio
michio
最後のアクティビティ: 2025 年 6 月 2 日

昨日 5/29 にお台場で MATLAB EXPO が開催されました。ご参加くださった方々ありがとうございました!
私は AI 関連のデモ展示で解説員としても立っておりましたが、立ち寄ってくださる方が絶えず、ずっと喋り続けてました。また、講演後に「さっきのすごくね?」という会話が漏れ聞こえてきたのがハイライト。
参加されたみなさま、印象に残ったこと・気になった講演・ポスター・デモ・新機能等あったら教えてください!(次回に向けて運営面での感想も)
以前のEXPOでも参加・聴講したことがある
67%
知り合いから聞いた
0%
MathWorksからのプロモーション,EXPOサイトで知った
0%
今年のEXPO会場でたまたま見かけた
0%
ライトニングトークって何?
33%
3 票
Lloyd Stagg
Lloyd Stagg
最後のアクティビティ: 2025 年 5 月 6 日

I like this problem by James and have solved it in several ways. A solution by Natalie impressed me and introduced me to a new function conv2. However, it occured to me that the numerous test for the problem only cover cases of square matrices. My original solutions, and Natalie's, did niot work on rectangular matrices. I have now produced a solution which works on rectangular matrices. Thanks for this thought provoking problem James.
I wanted to turn a Markdown nested list of text labels:
- A
- B
- C
- D
- G
- H
- E
- F
- Q
into a directed graph, like this:
Visualization of a directed graph representing a nest list of text labels
Here is my blog post with some related tips for doing this, including text I/O, text processing with patterns, and directed graph operations and visualization.
Large Languge model with MATLAB, a free add-on that lets you access LLMs from OpenAI, Azure, amd Ollama (to use local models) on MATLAB, has been updated to support OpenAI GPT-4.1, GPT-4.1 mini, and GPT-4.1 nano.
According to OpenAI, "These models outperform GPT‑4o and GPT‑4o mini across the board, with major gains in coding and instruction following. They also have larger context windows—supporting up to 1 million tokens of context—and are able to better use that context with improved long-context comprehension."
You can follow this tutorial to create your own chatbot with LLMs with MATLAB.
What would you build with the latest update?
The topic recently came up in a MATLAB Central Answers forum thread, where community members discussed how to programmatically control when the end user can close a custom app. Imagine you need to prevent app closure during a critical process but want to allow the end user to close the app afterwards. This article will guide you through the steps to add this behavior to your app.
A demo is attached containing an app with a state button that, when enabled, disables the ability to close the app.
Steps
1. Add a property that stores the state of the closure as a scalar logical value. In this example, I named the property closeEnabled. The default value in this example is true, meaning that closing is enabled. -- How to add a property to an app in app designer
properties (Access = private)
closeEnabled = true % Flag that controls ability to close app
end
2. Add a CloseRequest function to the app figure. This function is called any time there is an attempt to close the app. Within the CloseRequest function, add a condition that deletes the app when closure is enabled. -- How to add a CloseRequest function to an app figure in app designer
function UIFigureCloseRequest(app, event)
if app.closeEnabled
delete(app)
end
3. Toggle the value of the closeEnabled property as needed in your code. Imagine you have a "Process" button that initiates a process where it is crucial for the app to remain open. Set the closeEnabled flag to false (closure is disabled) at the beginning of the button's callback function and then set it to true at the end (closure is enabled).
function ProcessButtonPress(app, event)
app.closeEnabled = false;
% MY PROCESS CODE
app.closeEnabled = true;
end
Handling Errors: There is one trap to keep in mind in the example above. What if something in the callback function breaks before the app.closeEnabled is returned to true? That leaves the app in a bad state where closure is blocked. A pro move would be to use a cleanupObj to manage returning the property to true. In the example below, the task to return the closeEnabled property to true is managed by the cleanup object, which will execute that command when execution is terminated in the ProcessButtonPress function—whether execution was terminated by error or by gracefully exiting the function.
function ProcessButtonPress(app, event)
app.closeEnabled = false;
cleanupClosure = onCleanup(@()set(app,'closeEnabled',true));
% MY CODE
end
Force Closure: If the CloseRequest function is preventing an app from closing, here are a couple of ways to force a closure.
  1. If you have the app's handle, use delete(app) or close(app,'force'). This will also work on the app's figure handle.
  2. If you do not have the app's handle, you can use close('all','force') to close all figures or use findall(groot,'type','figure') to find the app's figure handle.
Provide insightful answers
9%
Provide label-AI answer
9%
Provide answer by both AI and human
21%
Do not use AI for answers
46%
Give a button "chat with copilot"
10%
use AI to draft better qustions
5%
1561 票
I have written, tested, and prepared a function with four subsunctions on my computer for solving one of the problems in the list of Cody problems in MathWorks in three days. Today, when I wanted to upload or copy paste the codes of the function and its subfunctions to the specified place of the problem of Cody page, I do not see a place to upload it, and the ability to copy past the codes. The total of the entire codes and their documentations is about 600 lines, which means that I cannot and it is not worth it to retype all of them in the relevent Cody environment after spending a few days. I would appreciate your guidance on how to enter the prepared codes to the desired environment in Cody.
Mike Croucher
Mike Croucher
最後のアクティビティ: 2025 年 4 月 3 日

Me: If you have parallel code and you apply this trick that only requires changing one line then it might go faster.
Reddit user: I did and it made my code 3x faster
Not bad for just one line of code!
Which makes me wonder. Could it make your MATLAB program go faster too? If you have some MATLAB code that makes use of parallel constructs like parfor or parfeval then start up your parallel pool like this
parpool("Threads")
before running your program.
The worst that will happen is you get an error message and you'll send us a bug report....or maybe it doesn't speed up much at all....
....or maybe you'll be like the Reddit user and get 3x speed-up for 10 seconds work. It must be worth a try...after all, you're using parallel computing to make your code faster right? May as well go all the way.
In an artificial benchmark I tried, I got 10x speedup! More details in my recent blog post: Parallel computing in MATLAB: Have you tried ThreadPools yet? » The MATLAB Blog - MATLAB & Simulink
Give it a try and let me know how you get on.