PythonユーザーのためのMatlab対応表を作っていこうと思います。
Matlabのドキュメントは初心者殺しっぽいところがありますよね...
徐々に増やしていく予定です。
list
宣言・要素の追加
a = [1, 2] a.append(3) # a = [1, 2, 3] a.append(4) # a = [1, 2, 3, 4]
a = [1, 2]; a(end+1) = 3; % a = [1, 2, 3] a(end+1) = 4; % a = [1, 2, 3, 4] 文字列を扱う場合はセル配列を用いる a = {'a', 'b'}; a{end+1} = 'c'; % a = {'a', 'b', 'c'} % a = ['a', 'b'] は a='ab' となる
リストの結合
a = [1, 2] b = [3, 4] c = a + b # c = [1, 2, 3, 4]
a = [1, 2]; b = [3, 4]; c = [a, b]; % c = [1, 2, 3, 4] % 列ベクトル(行列)の場合 a = [1; 2]; b = [3; 4]; c = [a; b]; % c = [1; 2; 3; 4]
set
重複する要素の削除
a = [1, 2, 3, 1, 2, 3] a = set(a) # a = {1 ,2, 3}
a = [1, 2, 3, 1, 2, 3]; a = unique(a); % a = [1, 2, 3];
要素の存在判定
a = {1, 2, 3} 1 in a >> True 4 in a >> False
a = [1, 2, 3]; ismember(a, 1); >> ans = 1×3 の logical 配列 1 0 0 % なので, 以下のようにすればよい any(ismember(a, 1); >> ans = logical 1
もしくは, 真偽が逆になるが
isempty(find(a == 4)) >> ans = logical 1
dictionary
辞書の宣言・要素の追加
a = {'a': 0, 'b': 1} a['c'] = 3 # a = {'a': 0, 'b': 1, 'c': 3} del a['c'] # a = {'a': 0, 'b': 1}
k = {'a', 'b'}; v = {0, 1}; a = containers.Map(k, v); % a = {'a': 0, 'b': 1} a('c') = 3; % a = {'a': 0, 'b': 1, 'c': 3} remove(a, 'c') % a = {'a': 0, 'b': 1}
function
ローカル関数
返り値1つ
def f(x): return x**2
function r = f(x) r = x; end
返り値複数
def f(x): return x, x**2
function [a, b] = f(x) a = x; b = x**2; end
ラムダ式関数
f = lambda x: x**2
f = @(x)x**2 % 暗黙的に多次元ベクトルに対応 f = @(x)x(1)**2 + x(2)**2
関数のデフォルト引数
def f(a, b, c=1): return a + b + c >> f(4, 3, 2) >> 9 >> f(4, 3) >> 8
r = function f(a, b, c) if nargin == 2 c = 1; end r = a + b + c; end
文字列
結合
s = ['Hello ', 'World'] ''.join(s) >> 'Hello World'
s = ["Hello ", "World"] join(s, "") >> "Hello World"
繰り返し
s = '*' * 100
s = repmat("*", 1, 100); s = join(s, "")
分割
s = 'apple orange grape' s.split() >> ['apple', 'orange', 'grape'] s.split('e') >> ['appl', ' orang', ' grap', '']
s = 'apple orange grape' strsplit(s) >> 1×3 の cell 配列 >> {'apple'} {'orange'} {'grape'} strsplit(s, "e") >> 1×4 の cell 配列 >> {'appl'} {' orang'} {' grap'} {0×0 char}