行列と基本操作
行列とベクトルの作成
MATLAB(MATrix LABoratory)はすべての変数を行列として扱います。ベクトルは1xNまたはNx1の行列です。行の要素を区切るにはスペースまたはカンマ、新しい行にはセミコロンを使います。zeros、ones、eye、rand、magicは一般的なテスト行列を作成します。コロン演算子 start:step:stop は範囲を生成します(デフォルトのステップは1)。linspace(a, b, n)はn個の等間隔の点を作成します — プロット軸に最適です。
% row vector
v = [1 2 3 4 5];
% column vector (semicolon = new row)
c = [1; 2; 3];
% 3x3 matrix
A = [1 2 3; 4 5 6; 7 8 9];
% special matrices
Z = zeros(3); % 3x3 zeros
O = ones(2, 4); % 2x4 ones
I = eye(3); % 3x3 identity
R = rand(2, 3); % 2x3 uniform random
N = randn(4); % 4x4 normal random
M = magic(4); % 4x4 magic square
D = diag([1 2 3]); % diagonal matrix
% linear spacing
l = linspace(0, 1, 5); % [0 0.25 0.5 0.75 1]
r = 0:0.5:2; % [0 0.5 1 1.5 2]行列のインデックス付けとスライシング
MATLABは1始まりのインデッ クスです(0始まりではありません)。コロン : は「すべて」を意味します — A(:,2)は第2列全体です。A(1:3, :)は行1-3を選択します。'end'はその次元の最後のインデックスを参照します。論理インデックス(A(A > 5))は非常に強力です — 条件に一致する要素を抽出または変更します。findは非ゼロ/真の要素のインデックスを返し、2つの出力を指定すると行と列を別々に返します。
A = magic(4); % 4x4 magic square
% single element (1-indexed!)
A(2, 3) % row 2, col 3
% entire row or column
A(1, :) % first row (all columns)
A(:, 2) % second column (all rows)
% submatrix
A(1:2, 2:4) % rows 1-2, cols 2-4
% linear indexing (column-major)
A(5) % 5th element counting down columns
% end keyword
A(end, :) % last row
A(:, end-1) % second-to-last column
% logical indexing
A(A > 10) % all elements > 10 (as vector)
A(A > 10) = 0; % set large elements to 0
% find indices
[r, c] = find(A == 16) % row and col of value 16行列の演算
演算子の前のドット(.*)は要素ごとの演算にし、行列演算ではなくなります — これは初心者のバグの最大の原因です。A*Bは行列の乗算、A.*Bは対応する要素の乗算です。バックスラッシュ演算子(\)は線形システムを効率的かつ正確に解きます(LU分解) — inv(A)*bの代わりに常に x = A\b を使ってください。アポストロフィ(')は転置、複素行列には非共役転置の .' を使います。
A = [1 2; 3 4];
B = [5 6; 7 8];
% matrix operations
C = A + B; % addition
D = A - B; % subtraction
E = A * B; % matrix multiplication
F = A'; % transpose
G = A^2; % matrix power (A * A)
% element-wise operations (use the dot!)
H = A .* B; % element-wise multiply
I = A ./ B; % element-wise divide
J = A .^ 2; % element-wise power
K = 2 * A; % scalar multiply
% matrix functions
det(A) % determinant
inv(A) % inverse
pinv(A) % pseudo-inverse
rank(A) % rank
trace(A) % trace (sum of diagonal)
% solving linear systems Ax = b
b = [5; 11];
x = A \ b; % left division: solves A*x = b
x = inv(A) * b; % equivalent but slower行列の操作
[A B](スペース)による連結は水平に結合、[A; B](セミコロン)は垂直に結合します — 行作成の構文と対応しています。reshapeは列優先で埋めます(下から横へ)。flipud/fliplr/rot90は行列を向き変更します。repmatは行列をグリッドパターンでタイル状に並べます。行または列を [] に設定すると削除されます。sizeは次元、lengthは最大の次元、numelは総要素数を返します。
A = [1 2; 3 4];
B = [5 6; 7 8];
% concatenation
C = [A B]; % horizontal: [1 2 5 6; 3 4 7 8]
D = [A; B]; % vertical: 4x4
% reshape
E = reshape(1:12, 3, 4); % 3x4 matrix from 1..12
% flip and rotate
F = flipud(A); % flip up-down
G = fliplr(A); % flip left-right
H = rot90(A); % rotate 90 degrees
% repmat (tile)
I = repmat([1 2], 2, 3); % repeat [1 2] in a 2x3 grid
% size and length
[m, n] = size(A); % m=2, n=2
len = length(A); % max dimension = 2
num = numel(A); % total elements = 4
% remove rows/cols
A(2, :) = []; % delete row 2
A(:, 1) = []; % delete column 1要素ごとの関数とベクトル化
MATLABの強みはベクトル化です — 配列全体に一度に演算を適用し、内部で最適化されたC/Fortranで実行します。sin、exp、sqrtなどは自動的に要素ごとに動作します。sum/prod/max/minはデフォルトで列方向(次元1)に動作します。行方向には次元2を渡してください。A(:)は行列をベクトルに平坦化します。パフォーマンスのためにforループよりもベクトル化演算を常に優先してください — 10-100倍高速になることがあります。
% math functions operate element-wise
x = 0:0.1:2*pi;
y = sin(x); % sine of each element
z = exp(x); % exponential
w = sqrt(x); % square root
% rounding
round(3.7) % 4
floor(3.7) % 3
ceil(3.2) % 4
fix(-3.7) % -3 (toward zero)
% sums and products along dimensions
A = magic(3);
sum(A) % sum of each column (row vector)
sum(A, 2) % sum of each row (column vector)
sum(A(:)) % sum of ALL elements
prod(A) % product of each column
cumsum(A) % cumulative sum
% min, max, sort
[v, i] = max(A(:)) % max value and its index
sort(A, 'descend') % sort each column descending
% AVOID loops — vectorize!
% BAD: for i=1:1000, y(i)=sin(i); end
% GOOD:
i = 1:1000;
y = sin(i); % fast, vectorized制御フローと論理
If / Elseif / Else
MATLABはif/elseif/else/endを使います(注意:elseifは一語です)。論理演算子:&&(スカラーAND)、||(スカラーOR)、&(要素ごとのAND)、|(要素ごとのOR)、~(NOT、! ではありません)。文字列比較にはstrcmp/strcmpi(大文字小文字を区別しない)を使います — == 演算子は同じ長さの文字配列でのみ機能します。ブロックは常に'end'で終わらせます。
score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
else
grade = 'F';
end
disp(grade); % B
% logical operators: && (and), || (or), ~ (not)
if x > 0 && x < 10
disp('in range');
end
% compare strings with strcmp
if strcmp(name, 'Alice')
disp('hi Alice');
endFor と While ループ
forは指定された式の各列を反復します(ベクトルの場合は各要素)。whileは条件が真の間実行します。ループの前に配列を常に事前割り当てしてください(result = zeros(1,N)) — ループ内で配列を成長させると毎回の反復で再割り当てが発生し、非常に遅くなります。コロン演算子 1:5 は [1 2 3 4 5] を作成します。fprintfはフォーマット付き出力を表示します(Cのprintfのように)。
% for loop over a range
for i = 1:5
fprintf('i = %d\n', i);
end
% iterate over a vector
v = [10 20 30];
for val = v
disp(val);
end
% nested loop over a matrix
A = zeros(3, 3);
for r = 1:3
for c = 1:3
A(r, c) = r * c;
end
end
% while loop
n = 10;
while n > 1
n = n / 2;
fprintf('%.2f\n', n);
end
% preallocate for speed (IMPORTANT!)
result = zeros(1, 1000);
for i = 1:1000
result(i) = i^2;
endSwitch と Break/Continue
switchは値をcaseラベルと照合します — breakは不要です(C/Javaと異なり)。caseは複数値のセル配列を受け取れます。otherwiseがデフォルトです。breakは最内ループを抜けます。continueは次の反復にスキップします。try/catchはエラーを適切に処理します。MEは.messageと.identifierを持つMExceptionオブジェクトです。MATLABには三項演算子がありません — if/elseまたはインライン関数を使ってください。
% switch statement
method = 'linear';
switch method
case 'linear'
disp('using linear');
case 'cubic'
disp('using cubic');
case {'nearest', 'spline'}
disp('using nearest or spline');
otherwise
disp('unknown method');
end
% break and continue
for i = 1:10
if i == 5
break % exit the loop entirely
end
if mod(i, 2) == 0
continue % skip to next iteration
end
disp(i); % prints 1 3
end
% try-catch for error handling
try
x = 1 / 0; % may error
catch ME
fprintf('Error: %s\n', ME.message);
end論理演算とインデックス付け
論理インデックスはMATLABの強力な機能です — A(condition)は論理配列が真の要素を選択します。~= は「等しくない」(!= ではありません)。& と | は要素ごと、&& と || は短絡評価(スカラーのみ、if条件で推奨)です。findは真の値の線形インデックスを返します。any/allは次元に沿って一部/すべての要素が真かテストします。is*ファミリは型と特殊値(NaN、Inf)をテストします。
A = [1 2 3 4 5 6 7 8 9 10];
% comparison operators
A > 5 % logical array
A == 5
A ~= 5 % not equal (NOT !=)
A >= 3 & A <= 7 % element-wise AND
A < 3 | A > 7 % element-wise OR
% logical indexing (powerful!)
A(A > 5) % [6 7 8 9 10]
A(A > 5) = 0; % set elements > 5 to 0
A(mod(A, 2) == 0) % even numbers
% find indices
idx = find(A > 5); % indices of elements > 5
[r, c] = find(A > 5); % row and col (for matrices)
% any and all
any(A > 5) % true if ANY element > 5
all(A > 0) % true if ALL elements > 0
any(A > 5, 2) % per row
% is functions
isnan(x); isinf(x); isfinite(x);
isnumeric(x); ischar(x); iscell(x);文字列とフォーマット
MATLABには2種類の文字列型があります:char配列('text'、レガシー)とstringスカラー("text"、R2017+)。stringスカラーは操作に柔軟性があります。sprintfはフォーマット済み文字列を返し、fprintfはコンソールやファイルに出力します。一般的なフォーマット指定子:%s(文字列)、%d(整数)、%f(浮動小数点)、%.2f(小数2桁)、%e(科学表記)。strsplit/strjoinは区切りリストを処理します。num2str/mat2strは数値を文字列に変換します。
% string creation
s1 = 'Hello'; % char array
s2 = "World"; % string scalar (R2017+)
% concatenation
greeting = [s1 ', ' s2 '!']; % char array concat
full = s1 + " " + s2; % string concat
% formatting
name = 'Alice';
age = 30;
fprintf('Name: %s, Age: %d\n', name, age);
str = sprintf('Pi is %.2f', pi); % returns string
% common string functions
upper('hello') % HELLO
lower('WORLD') % world
strlength("hello") % 5 (string)
length('hello') % 5 (char array)
strcmp('a', 'a') % true
strfind('hello', 'll') % 3 (index)
strrep('cat', 'c', 'b') % bat
strsplit('a,b,c', ',') % {'a','b','c'}
strjoin({'a','b'}, '-') % a-b
num2str(42) % '42'関数とスクリプト
関数の定義
関数は同じ名前のファイル(関数addの場合はadd.m)、またはスクリプトファイルの末尾に配置する必要があります。最初の行が関数宣言です。関数は独自のワークスペースを持ちます(ベースワークスペースとは別)。nargin/nargoutでオプション引数を処理できます — narginは実際の入力数をカウントします。複数の出力は [a, b] = func() で取得します。より少ない出力で呼び出すと、余分なものは破棄されます。
% function in a file named 'add.m'
function result = add(a, b)
% ADD returns the sum of a and b
result = a + b;
end
% with multiple inputs and outputs
function [mn, mx, avg] = stats(v)
mn = min(v);
mx = max(v);
avg = mean(v);
end
% calling functions
s = add(3, 4); % 7
[lo, hi, mu] = stats([1 2 3 4 5]);
% capture only first output
minimum = stats([1 2 3]); % gets mn only
% nargin and nargout (number of args)
function y = power(x, n)
if nargin < 2
n = 2; % default value
end
y = x .^ n;
end無名関数とインライン関数
無名関数(@(args) expr)はインラインで定義される1行関数です — ファイルを作成せずにソルバー(fzero、integral、ode45)に渡すのに最適です。作成時にワークスペース変数をキャプチャします。関数ハンドル(@sin)で組み込みまたはユーザー関数を引数として渡せます。これは数値計算に不可欠です:integral(@(x) f(x), a, b) は定義した任意の関数を積分します。
% anonymous function (one-liner, no file needed)
square = @(x) x .^ 2;
square(5) % 25
square([1 2 3]) % [1 4 9]
% with multiple inputs
add = @(a, b) a + b;
add(3, 4) % 7
% capture variables from workspace
c = 10;
addc = @(x) x + c;
addc(5) % 15
% function handle to built-in
f = @sin;
f(pi/2) % 1
% pass functions as arguments
result = integral(@(x) x.^2, 0, 1); % integrate x^2 from 0 to 1
result = fzero(@(x) x^2 - 2, 1); % find root near 1
% array of function handles
funs = {@sin, @cos, @tan};
funs{1}(0) % 0スクリプトとライブスクリプト
スクリプトはベースワークスペースで実行されるコマンドのシーケンスです(独立したワークスペースを持つ関数とは異なります)。%% マーカーは独立して実行できる「セル」(セクション)を作成します — 段階的開発に最適です。ライブスクリプト(.mlx)はJupyterノートブックのようなものです:コード、フォーマット済みテキスト、数式、インラインプロットを1つのインタラクティブなドキュメントにまとめます。再利用可能なコードにはスクリプトより関数を優先してください。
% A script is just a sequence of commands in a .m file
% It shares the base workspace
% script: analyze_data.m
data = load('data.mat');
cleaned = data.values(data.values > 0);
mean_val = mean(cleaned);
fprintf('Mean: %.2f\n', mean_val);
plot(cleaned);
title('Cleaned Data');
% sections (cells) with %%
%% Initialize
x = linspace(0, 2*pi, 100);
%% Plot
plot(x, sin(x));
%% Analyze
disp(mean(sin(x)));
% Run a section: Ctrl+Enter (in editor)
% Live Scripts (.mlx): rich text, inline plots, equationsネスト関数とローカル関数
スクリプトはファイル末尾にローカル関数を含められます(R2016b以降) — そのファイル内でのみ表示されます。ネスト関数(別の関数内で定義)は親のワークスペースを共有し、その変数を読み取り変更できます — コールバックやアキュムレータに便利ですが、コードが追いにくくなる場合があります。関数ファイル内のローカル関数はそのファイル内でのみ表示されるヘルパーです。スクリプトを整理する ために多くのファイルを作成せずにローカル関数を使ってください。
% local functions in a script (must be at the end)
% main_script.m
x = 1:10;
y = process(x);
disp(y);
function r = process(v)
r = normalize(scale(v)); % calls another local function
end
function s = scale(v)
s = v * 10;
end
function n = normalize(v)
n = v / max(v);
end
% nested function (inside another function)
function outer(x)
y = 0;
function inner()
y = y + x; % can access outer's variables
end
inner();
disp(y);
end変数のスコープとグローバル
MATLABは値渡し(copy-on-modify)で引数を渡すため、関数が呼び出し元の変数を誤って変更できません — C/Pythonとは異なります。真に共有する状態にはglobalを使います(それを使用するすべての関数で宣言)、ただし引数渡しを優先してください。persistent変数は関数呼び出し間で値を保持します(Cのstaticのように) — カウンター、キャッシュ、メモ化に便利です。最初の呼び出しでisemptyチェックを使ってpersistent変数を初期化します。関数の戻り値やネスト関数を優先してグローバルを避けてください。