MATLAB チートシート(基礎編)
基本操作・ヘルプ
help 関数名 % コマンドウィンドウにヘルプ表示
doc 関数名 % ヘルプブラウザーでドキュメント表示
docsearch キーワード % ドキュメント検索
clc % コマンドウィンドウをクリア
clear % ワークスペースをクリア
clear 変数名 % 特定の変数を削除
who % ワークスペースの変数一覧
whos % 変数の詳細情報
配列・ベクトル・行列の作成
x = [1 2 3 4] % 行ベクトル
x = [1; 2; 3; 4] % 列ベクトル
A = [1 2; 3 4] % 2x2行列
x = 1:10 % 1から10まで(間隔1)
x = 0:0.1:1 % 0から1まで(間隔0.1)
x = linspace(0, 1, 100) % 0から1まで100個
zeros(3, 4) % 3x4のゼロ行列
ones(2, 3) % 2x3の1行列
eye(4) % 4x4単位行列
rand(3, 3) % 3x3ランダム行列(0-1の一様分布)
randn(2, 5) % 2x5ランダム行列(正規分布)
インデックスとスライス
A(2, 3) % 2行3列の要素
A(1, :) % 1行目全体
A(:, 2) % 2列目全体
A(1:3, :) % 1-3行目全体
A(end, :) % 最後の行
A([1 3], :) % 1行目と3行目
A(A > 5) % 5より大きい要素(論理インデックス)
配列の結合と変形
[A B] % 横に結合
[A; B] % 縦に結合
reshape(A, m, n) % mxnに変形
A' % 転置(複素数の場合は共役転置)
A.' % 転置(共役なし)
size(A) % 配列のサイズ [行数, 列数]
length(x) % ベクトルの長さ
numel(A) % 要素数
要素ごとの演算と行列演算
A + B % 行列の加算
A - B % 行列の減算
A * B % 行列の乗算
A .* B % 要素ごとの乗算
A ./ B % 要素ごとの除算
A .^ 2 % 要素ごとの累乗
A^2 % 行列の累乗
線形代数
inv(A) % 逆行列
det(A) % 行列式
rank(A) % ランク
trace(A) % トレース
norm(A) % ノルム
cond(A) % 条件数
A \ b % 線形方程式 Ax=b の解(バックスラッシュ演算子)
[V, D] = eig(A) % 固有値と固有ベクトル
[U, S, V] = svd(A) % 特異値分解
基本的な数学関数
sin(x), cos(x), tan(x) % 三角関数
asin(x), acos(x), atan(x) % 逆三角関数
exp(x) % 指数関数
log(x) % 自然対数
log10(x) % 常用対数
sqrt(x) % 平方根
abs(x) % 絶対値
sign(x) % 符号
round(x) % 四捨五入
floor(x) % 切り捨て
ceil(x) % 切り上げ
mod(a, b) % 剰余
rem(a, b) % 剰余(負の数の扱いが異なる)
統計関数
mean(x) % 平均値
median(x) % 中央値
mode(x) % 最頻値
std(x) % 標準偏差
var(x) % 分散
max(x) % 最大値
min(x) % 最小値
[val, idx] = max(x) % 最大値とそのインデックス
sum(x) % 合計
prod(x) % 積
cumsum(x) % 累積和
sort(x) % ソート
unique(x) % 一意な値
論理演算と比較
x == y % 等しい
x ~= y % 等しくない
x > y, x >= y % 大きい、以上
x < y, x <= y % 小さい、以下
x & y % AND(要素ごと)
x | y % OR(要素ごと)
~x % NOT
all(x) % すべて真か
any(x) % いずれか真か
find(x > 5) % 条件を満たすインデックス
文字列とテキスト
str = "Hello" % string配列(推奨)
str = 'Hello' % char配列
length(str) % 文字列長
strcat(s1, s2) % 文字列結合
sprintf('x = %d', 10) % 書式付き文字列
fprintf('x = %d\n', 10) % 書式付き出力
contains(str, "ell") % 部分文字列を含むか
replace(str, "old", "new") % 文字列置換
split(str, ",") % 分割
upper(str), lower(str) % 大文字・小文字変換
データ構造
% 構造体
s.name = 'John';
s.age = 30;
s = struct('name', 'John', 'age', 30);
% Cell配列
c = {1, 'text', [1 2 3]};
c{1} % Cell要素へのアクセス
% Table
T = table([1;2;3], [10;20;30], 'VariableNames', {'ID', 'Value'});
T.ID % 列へのアクセス
T(1, :) % 行へのアクセス
ファイル入出力
% CSVファイル
T = readtable('data.csv'); % CSV読み込み(table)
writetable(T, 'output.csv'); % CSV書き込み
M = readmatrix('data.csv'); % CSV読み込み(行列)
% Excelファイル
T = readtable('data.xlsx'); % Excel読み込み
writetable(T, 'output.xlsx'); % Excel書き込み
% MATファイル
save('data.mat', 'x', 'y'); % 変数保存
load('data.mat'); % 変数読み込み
save('data.mat', 'x', '-append'); % 追加保存
% テキストファイル
data = readlines('file.txt'); % テキスト読み込み(string配列)
writelines(data, 'output.txt'); % テキスト書き込み
% 画像ファイル
img = imread('image.jpg'); % 画像読み込み
imwrite(img, 'output.png'); % 画像保存
imshow(img); % 画像表示
2Dプロット
plot(x, y) % 線グラフ
plot(x, y, 'r--') % 赤い破線
scatter(x, y) % 散布図
bar(x) % 棒グラフ
histogram(x) % ヒストグラム
area(x, y) % エリアプロット
% プロットの装飾
title('タイトル');
xlabel('X軸ラベル');
ylabel('Y軸ラベル');
legend('データ1', 'データ2');
grid on % グリッド表示
xlim([0 10]) % X軸範囲
ylim([-1 1]) % Y軸範囲
set(gca, 'XScale', 'log') % 対数スケール
% 複数プロット
hold on % プロットを重ねる
plot(x1, y1);
plot(x2, y2);
hold off
subplot(2, 2, 1) % 2x2のサブプロット、1番目
tiledlayout(2, 2) % タイルレイアウト(R2019b以降、推奨)
nexttile
3Dプロット
plot3(x, y, z) % 3D線グラフ
scatter3(x, y, z) % 3D散布図
surf(X, Y, Z) % サーフェスプロット
mesh(X, Y, Z) % メッシュプロット
contour(X, Y, Z) % 等高線図
colormap jet % カラーマップ変更
colorbar % カラーバー表示
view(45, 30) % 視点角度設定
プログラミング制御構文
% if文
if x > 0
disp('正');
elseif x < 0
disp('負');
else
disp('ゼロ');
end
% switch文
switch x
case 1
disp('1');
case 2
disp('2');
otherwise
disp('その他');
end
% forループ
for i = 1:10
disp(i);
end
% whileループ
while x < 100
x = x * 2;
end
% ループ制御
break % ループ脱出
continue % 次の反復へ
関数定義
% 基本的な関数(ファイル名: myFunction.m)
function y = myFunction(x)
y = x^2 + 2*x + 1;
end
% 複数出力
function [mean_val, std_val] = stats(x)
mean_val = mean(x);
std_val = std(x);
end
% 無名関数(ラムダ関数)
f = @(x) x^2 + 1;
result = f(5); % 26
エラーハンドリング
% try-catch文
try
result = risky_operation();
catch ME
disp(ME.message);
end
% エラーの発生
error('エラーメッセージ');
% 警告の表示
warning('警告メッセージ');
% アサーション
assert(x > 0, 'xは正でなければなりません');
データクリーニング
% 欠損値処理
isnan(x) % NaNかどうか
ismissing(x) % 欠損値かどうか
rmmissing(x) % 欠損値を削除
fillmissing(x, 'linear') % 欠損値を補間
% 外れ値処理
isoutlier(x) % 外れ値検出
rmoutlier(x) % 外れ値削除
% 正規化
normalize(x) % 正規化(平均0、標準偏差1)
rescale(x, 0, 1) % 0-1にスケーリング
% 重複削除
unique(x) % 重複削除
便利なユーティリティ
tic; ... ; toc % 実行時間測定
pause(2) % 2秒停止
input('値を入力: ') % ユーザー入力
disp(x) % 変数表示
fprintf('値: %d\n', x) % 書式付き表示
which 関数名 % 関数のパス表示
cd % カレントディレクトリ表示
cd フォルダ名 % ディレクトリ変更
pwd % カレントディレクトリのパス
dir % ファイル一覧
delete('file.txt') % ファイル削除
数値解析
% 多項式
p = [1 -3 2]; % x^2 - 3x + 2
roots(p) % 多項式の根
polyval(p, x) % 多項式の値
% 補間
yi = interp1(x, y, xi) % 1次元補間
yi = interp1(x, y, xi, 'spline') % スプライン補間
% 数値積分
integral(@(x) x.^2, 0, 1) % 定積分
% 微分
gradient(y, x) % 数値微分
% 根の探索
fzero(@(x) x^2-2, 1) % 方程式の根
% 最適化
fminbnd(@(x) (x-2)^2, 0, 4) % 1変数最小化
デバッグ
dbstop in ファイル名 at 行番号 % ブレークポイント設定
dbcont % デバッグ継続
dbstep % ステップ実行
dbquit % デバッグ終了
keyboard % コード内でデバッグモード開始
ヒント:
- セミコロン(;)を行末に付けると結果を表示しない
-
%でコメント、%%でセクション区切り - 変数名は大文字小文字を区別
- 配列のインデックスは1から始まる(0ではない)
MATLAB CI/CD チートシート
基本コマンド
MATLAB バッチ実行
# 基本的なバッチ実行
matlab -batch "command"
# テスト実行
matlab -batch "runtests"
# 特定のテストスクリプト実行
matlab -batch "results = runtests('tests'); assertSuccess(results)"
# ビルドツール実行
matlab -batch "buildtool"
テスト実行コマンド
% すべてのテストを実行
runtests
% 特定フォルダのテストを実行
runtests('tests')
% テスト結果を変数に格納
results = runtests('tests');
% カバレッジ付きでテスト実行
import matlab.unittest.TestRunner
import matlab.unittest.plugins.CodeCoveragePlugin
runner = TestRunner.withTextOutput;
runner.addPlugin(CodeCoveragePlugin.forFolder('src'));
results = runner.run(testsuite('tests'));
GitHub Actions
基本ワークフロー構造
name: MATLAB CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: matlab-actions/setup-matlab@v2
- uses: matlab-actions/run-tests@v2
MATLAB公式アクション
setup-matlab@v2 - MATLAB環境セットアップ
- uses: matlab-actions/setup-matlab@v2
with:
release: R2024a # MATLABバージョン指定
products: | # 必要なツールボックス
Signal_Processing_Toolbox
Parallel_Computing_Toolbox
cache: true # インストールをキャッシュ
run-tests@v2 - テスト実行
- uses: matlab-actions/run-tests@v2
with:
source-folder: src # ソースフォルダ
test-results-junit: test-results.xml
code-coverage-cobertura: coverage.xml
select-by-folder: tests # テストフォルダ
run-build@v2 - ビルドツール実行
- uses: matlab-actions/run-build@v2
with:
tasks: test check package # 実行タスク
build-options: -continueOnFailure
run-command@v2 - カスタムコマンド実行
- uses: matlab-actions/run-command@v2
with:
command: |
addpath('src');
results = runtests('tests');
assertSuccess(results);
マトリックスビルド(複数バージョン/OS)
strategy:
matrix:
release: [R2023b, R2024a, R2024b]
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: matlab-actions/setup-matlab@v2
with:
release: ${{ matrix.release }}
アーティファクト保存
- uses: actions/upload-artifact@v4
with:
name: test-results
path: |
test-results.xml
coverage.xml
*.log
カバレッジバッジ追加
- name: Generate Coverage Badge
uses: matlab-actions/run-command@v2
with:
command: |
results = runtests('tests', 'CodeCoveragePlugin', ...
CodeCoveragePlugin.forFolder('src'));
generateCoverageBadge(results);
GitLab CI/CD
基本パイプライン構造
image: mathworks/matlab:latest
stages:
- test
- build
test:
stage: test
script:
- matlab -batch "runtests"
artifacts:
reports:
junit: test-results.xml
paths:
- coverage.xml
GitLabコンポーネント使用
include:
- component: mathworks/gitlab-ci-cd/run-matlab-tests@v1
test:
stage: test
extends: .run-matlab-tests
variables:
SOURCE_FOLDER: src
TEST_FOLDER: tests
Docker Executor方式
test:
image: mathworks/matlab:R2024a
script:
- matlab -batch "addpath('src'); results = runtests('tests'); assertSuccess(results)"
セルフホストランナー
test:
tags:
- matlab-runner # ランナータグ
script:
- matlab -batch "runtests"
Jenkins
パイプライン形式
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'matlab -batch "runtests"'
}
}
}
}
フリースタイルプロジェクト
# ビルドステップでシェル実行
matlab -batch "addpath('src'); results = runtests('tests'); assertSuccess(results)"
ライセンス管理
バッチライセンストークン設定
GitHub Actions
env:
MLM_LICENSE_TOKEN: ${{ secrets.MLM_LICENSE_TOKEN }}
GitLab CI/CD
variables:
MLM_LICENSE_TOKEN: $GITLAB_MLM_LICENSE_TOKEN
ネットワークライセンス
# ライセンスサーバー指定
export MLM_LICENSE_FILE=port@server
matlab -batch "runtests"
ビルドツール (buildtool)
buildfile.m の基本構造
function plan = buildfile
plan = buildplan(localfunctions);
% デフォルトタスク
plan.DefaultTasks = "test";
% タスク依存関係
plan("test").Dependencies = "check";
plan("package").Dependencies = "test";
end
function checkTask(~)
% コード品質チェック
end
function testTask(~)
% テスト実行
results = runtests('tests');
assertSuccess(results);
end
function packageTask(~)
% パッケージング
end
ビルドツール実行
# デフォルトタスク実行
matlab -batch "buildtool"
# 特定タスク実行
matlab -batch "buildtool test"
# 複数タスク実行
matlab -batch "buildtool test package"
# 失敗時も継続
matlab -batch "buildtool -continueOnFailure"
テストフレームワーク
テストクラス作成
classdef MyTest < matlab.unittest.TestCase
methods(Test)
function testAddition(testCase)
result = myFunction(2, 3);
testCase.verifyEqual(result, 5);
end
end
end
パラメータ化テスト
classdef ParameterizedTest < matlab.unittest.TestCase
properties(TestParameter)
input = {1, 2, 3};
expected = {2, 4, 6};
end
methods(Test)
function testDouble(testCase, input, expected)
result = input * 2;
testCase.verifyEqual(result, expected);
end
end
end
静的コード解析
コードアナライザー
% コード品質チェック
checkcode('myFunction.m')
% すべてのMファイルをチェック
files = dir('**/*.m');
for i = 1:length(files)
results = checkcode(fullfile(files(i).folder, files(i).name));
if ~isempty(results)
disp(results);
end
end
MATLAB Code Analyzer
# CI環境での実行
matlab -batch "results = checkcode('src/*.m', '-modifiedcyclomaticomplexity'); assert(isempty(results))"
MEXファイルコンパイル
基本コンパイル
matlab -batch "mex myFunction.c"
CI環境でのクロスプラットフォームコンパイル
- name: Compile MEX
run: matlab -batch "mex -setup; mex myFunction.c"
パッケージング
ツールボックスパッケージ作成
% プロジェクトファイルから
matlab.addons.toolbox.packageToolbox('MyToolbox.prj', 'MyToolbox.mltbx')
CI環境での自動パッケージング
matlab -batch "matlab.addons.toolbox.packageToolbox('MyToolbox.prj', 'MyToolbox.mltbx')"
トラブルシューティング
よくあるエラーと対処法
テストが見つからない
# パス追加を確認
matlab -batch "addpath(genpath('tests')); runtests"
ライセンスエラー
# トークンが設定されているか確認
echo $MLM_LICENSE_TOKEN
# ネットワークライセンスの場合
export MLM_LICENSE_FILE=27000@license-server
ツールボックスが見つからない
# setup-matlabでproductsを指定
- uses: matlab-actions/setup-matlab@v2
with:
products: Signal_Processing_Toolbox
YAMLシンタックスエラー
# オンラインバリデーター使用
# https://www.yamllint.com/
# インデント確認(スペース2つ)
セキュリティベストプラクティス
シークレット管理
# GitHub Secretsを使用
env:
MLM_LICENSE_TOKEN: ${{ secrets.MLM_LICENSE_TOKEN }}
API_KEY: ${{ secrets.API_KEY }}
# 直接記述しない(NG例)
env:
MLM_LICENSE_TOKEN: "12345-67890-12345" # NG!
ブランチ保護
# mainブランチへの直接プッシュを禁止
# Pull Requestでのテスト必須化
on:
pull_request:
branches: [main]
パフォーマンス最適化
キャッシュ活用
# GitHub Actions
- uses: matlab-actions/setup-matlab@v2
with:
cache: true
# 依存関係のキャッシュ
- uses: actions/cache@v4
with:
path: ~/.matlab
key: ${{ runner.os }}-matlab-${{ hashFiles('**/requires.txt') }}
並列テスト実行
% Parallel Computing Toolbox使用
parpool('local', 4);
results = runtests('tests', 'UseParallel', true);
delete(gcp);
モニタリングとレポート
テスト結果の可視化
# JUnit形式のテスト結果
- uses: matlab-actions/run-tests@v2
with:
test-results-junit: test-results/results.xml
# レポートとして表示
- uses: dorny/test-reporter@v1
if: always()
with:
name: MATLAB Tests
path: test-results/*.xml
reporter: java-junit
カバレッジレポート
- name: Upload Coverage
uses: codecov/codecov-action@v4
with:
files: coverage.xml
flags: matlab
クイックリファレンス
よく使うコマンド一覧
# テスト実行
matlab -batch "runtests"
# ビルド実行
matlab -batch "buildtool"
# パッケージング
matlab -batch "buildtool package"
# カバレッジ付きテスト
matlab -batch "import matlab.unittest.TestRunner; import matlab.unittest.plugins.CodeCoveragePlugin; runner = TestRunner.withTextOutput; runner.addPlugin(CodeCoveragePlugin.forFolder('src')); runner.run(testsuite('tests'))"
# MEXコンパイル
matlab -batch "mex myFunction.c"
# コード解析
matlab -batch "checkcode('src/*.m')"
環境変数
MLM_LICENSE_TOKEN # バッチライセンストークン
MLM_LICENSE_FILE # ネットワークライセンスサーバー
MATLAB_RELEASE # MATLABバージョン(R2024a等)


