Google Colaboratory で MATLAB を使う
MATLAB は,(オンラインでいつでもどこからでも使えるとは宣伝しているが)無料では使えないらしい。
Google Colaboratory で octave を介すれば,ちょっと面倒な気はするが,無料で使えるようだ。
Matlab in Google Colab.ipynb - Colaboratory
以下のように行えばよい。
octave のインストール
以下を行う。
!apt install octave
もし,全くのはじめてなら数分かかるが,二回目以降はすぐ終わる。
二回目以降は,以下のような表示が出れば準備万端
Reading package lists... Done
Building dependency tree
Reading state information... Done
octave is already the newest version (4.2.2-1ubuntu1).
The following package was automatically installed and is no longer required:
libnvidia-common-460
Use 'apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 49 not upgraded.
処理系の動作
Google Colaboratory で MATLLAB を使う基本は以下の 2 つを必要に応じて行うことである。
-
%%writefile ファイル名.m
でコードをファイルに書き込む -
!octave -W ファイル名.m
で実行結果を表示する
例
二次元クロス集計表の独立性の検定を行う関数を定義し,それを用いて検定を行う例を示す。
まずは関数を定義する。MATLAB の慣例で関数名とファイル名を同じにするそうなので,ChiSquareTest.m
に ChiSquareTest
関数の定義を書き込む。
この処理系の制約(?)で,期待されるとおりの処理結果にならない関数などがあるので,姑息な手段でエラー回避をする必要があるかもしれない。
%%writefile ChiSquareTest.m
function [chisq, df, p] = ChiSquareTest(x)
[nrow , ncol] = size(x);
df = (nrow - 1) * (ncol - 1);
colsums = sum(x, 1);
rowsums = sum(x, 2);
n = sum(rowsums);
expectations = (rowsums * colsums) / n;
Zscores = (x .- expectations) .^ 2 ./ expectations;
% sum(Zscores, 'all') % エラー(このバージョンにはないため)
% sum(Zscores, [1 2]) % なぜか適正に動かない
chisq = sum(sum(Zscores));
p = 1 - chi2cdf(chisq, df); % この環境では icdf はインストールされていないため
end
Overwriting ChiSquareTest.m
他の言語ならば,上の ChiSquareTest.m に関数呼び出しのテストを書き込めるが,MATLAB ではそれではだめなようなので,テストは別のファイルに書き込む(untitled.m
)。
%%writefile untitled.m
x = [55 22 16 7; 40 32 24 4];
[chisq, df, p] = ChiSquareTest(x)
Overwriting untitled.m
実行するために以下のようにする。
!octave -W untitled.m
chisq = 6.6385
df = 3
p = 0.084359
結果をきれいな書式で書き出す方法は,まだ探索していない。