第1回 MATLAB seminar 2022年08月02日
最終更新:2022/08/06
基礎文法
去年は, 以下の教科書を使って基礎文法を勉強したが, そこまで丁寧にやらなくても学生はマスターしてくれそうだったので, 軽く数値計算に必要な文法を学んだ. ( MATLAB/Scilabで理解する数値計算 )
MATLAB
%% 1 量 % scalar 1 2 3 a = 5; % vector % yoko [1 2 3 4 5] [1, 2, 3, 4, 5] b = [1, 2, 3, 4, 5]; % tate [1; 2; 3; 4; 5] b = [1; 2; 3; 4; 5]; % sucsession b = 1:10; b = 1:2:10; b = 1:0.1:10; b = linspace(1, 10, 100); % 行列 [1 2 3; 8 7 6; 9 7 5] A = [1 2 3; 8 7 6; 9 7 5]; [1 2 3; 8 7 6; 9 7] % error % 特殊な行列 zeros(4, 3) ones(5, 3) eye(5) magic(5) randn(5, 5) % 多次元配列 zeros(3, 3, 3) %% 2 量と量の演算 % a スカラ一つ a = 5; 1/a -a % b ベクトル一つ b = [1, 3, 7]; -b 1/b % error 1 ./ b % elementwise b' % transpose norm(b) % 絶対値 cumsum(b) diff(b) % c 行列だけ A = magic(3); -A % = -1 * A det(A) trace(A) inv(A) A' % transpose eig(A) % 固有値 rank(A) % 行列の抽出と代入 A = randi(6, 3, 10); A(2, 1:2:10); A(:, 1:2:end); A(1:2, 1:2) = ones(2, 2); %% % d scalar vs scalar a = 4; b = 3; a + b a * b a - b a / b a^b mod(a, b) % e scalar * vector a = 4; b = [1, 2, 5, 7]; a + b a - b a * b a ./ b b / a a .^ b % f scalar vs matrix a = 4; A = magic(3); a + A a - A a * A a / A % error try a ./ A % or a * inv(A) % but A / a % is ok A .^ a % g vector vs vector v = [3, 4, 5, 1] w = [2, 3, 1, 1] v + w % v - w v * w' % 内積 = dot() v' * w v .* w' v = [3, 4, 5] w = [2, 3, 1] cross(v, w) v .^ w % h vector * % skip % i matrix * matrix A = randi(10, 3, 3) B = randi(10, 3, 3) A + B % A - B A * B A .* B % Hadamard product A/B A .^ B trace(A*B) == trace(B*A) %% 特殊関数 a = 0.5; sin(a) cos(a) tanh(a) exp(a) gamma(a) pi exp(1) besseli %% 乱数 randn % 正規分布 data = randn(1000, 1); histogram(data) data2 = data .^ 2; % 正規分布の自乗、つまりχ自乗 histogram(data2); data = rand(1000, 1); % 一様分布 histogram(data) randi([2, 4], 5, 5) % 整数 %% for, if for I = 1:10 disp(I) end for I = 1:3:10 disp(I) end for I = 1:10 if mod(I, 2) == 0 disp(I) end end %% graph % https://jp.mathworks.com/help/matlab/creating_plots/types-of-matlab-plots.html load sunspot; d = sunspot; plot(d(:, 1), d(:, 2)) scatter(d(:, 1), d(:, 2)) %% sin(x) N = 10000; x = linspace(0, 4*pi, N); y = sin(x); plot(x, y)