サブロウ丸

Sabrou-mal サブロウ丸

主にプログラミングと数学

PythonユーザーのためのMatlab対応表


PythonユーザーのためのMatlab対応表を作っていこうと思います。
Matlabのドキュメントは初心者殺しっぽいところがありますよね...

徐々に増やしていく予定です。

list

宣言・要素の追加

python

a = [1, 2]
a.append(3) # a = [1, 2, 3]
a.append(4) # a = [1, 2, 3, 4]


matlab

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' となる


リストの結合

python

a = [1, 2]
b = [3, 4]
c = a + b # c = [1, 2, 3, 4]


matlab

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

重複する要素の削除

python

a = [1, 2, 3, 1, 2, 3]
a = set(a) # a = {1 ,2, 3}

matlab

a = [1, 2, 3, 1, 2, 3];
a = unique(a); % a = [1, 2, 3];

要素の存在判定

python

a = {1, 2, 3}
1 in a
>> True
4 in a
>> False

matlab

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

辞書の宣言・要素の追加

python

a = {'a': 0, 'b': 1}
a['c'] = 3 # a = {'a': 0, 'b': 1, 'c': 3}
del a['c'] # a = {'a': 0, 'b': 1}

matlab

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つ

python

def f(x):
    return x**2

matlab

function r = f(x)
    r = x;
end


返り値複数

python

def f(x):
    return x, x**2

matlab

function [a, b] = f(x)
    a = x;
    b = x**2;
end


ラムダ式関数

python

f = lambda x: x**2

matlab

f = @(x)x**2

% 暗黙的に多次元ベクトルに対応
f = @(x)x(1)**2 + x(2)**2


関数のデフォルト引数

python

def f(a, b, c=1):
    return a + b + c

>> f(4, 3, 2)
>> 9
>> f(4, 3)
>> 8

matlab

r = function f(a, b, c)
    if nargin == 2
        c = 1;
    end
    r = a + b + c;
end



文字列

結合

python

s = ['Hello ', 'World']
''.join(s)
>> 'Hello World'

matlab

s = ["Hello ", "World"]
join(s, "")
>> "Hello World"


繰り返し

python

s = '*' * 100

matlab

s = repmat("*", 1, 100);
s = join(s, "")


分割

python

s = 'apple orange grape'
s.split()
>> ['apple', 'orange', 'grape']

s.split('e')
>> ['appl', ' orang', ' grap', '']

matlab

s = 'apple orange grape'
strsplit(s)
>>  1×3 の cell 配列
>>    {'apple'}    {'orange'}    {'grape'}

strsplit(s, "e")
>>  1×4 の cell 配列
>>    {'appl'}    {' orang'}    {' grap'}    {0×0 char}