Pythonを長い間使っているがMatlab/Simulinkをやる必要が生じたため、自らの勉強の記録として気づいたことを書いておく。
indexing
Python is zero-based indexing while Matlab employs one-based indexing.
Python
a = [10, 20, 30]
a[0]
# 10
Matlab
a = [10 20 30]
a(1)
# 10
List or Array creation
Python range does not include the last value while Matlab does. Also, the order of the range is not the same. Python range-> initial value: last value, delta, Matlab-> initial value:delta:last value.
Python
a = list(range(0, 10, 2))
a
# 0, 2, 4, 6, 8
Matlab
a = 0:2:8
a
# 0, 2, 4, 6, 8
Array referencing
Python uses multiple parentheses to refence multiple dimension array (actually list) while Matlab uses only one set of parentheses.
Python
a = [[1, 2], [3, 4]
a[0][0]
# 1
Matlab
a = [1 2;3 4]
a(1,1)
# 1
sizeとlen
Python uses len for getting the length of an list while Matlab uses size. Matlab returns row size and column size simultaneously.
Python
a = [3, 4, 5, 6]
len(a)
# 4
Matlab
a = [3 4 5 6]
size(a)
# 1 4
dictとstruct
Matlab has struct type, which allows us to use flexible structure of data. Python does not have struct, but there are some ways to implement a similar data structure – dictionary, class, namedtuple, etc.
Matlab
condition.id = 5
condition.name = 'bike1'
condition.date = '2021/10/2'
# condition = struct with fields:
# id: 5
# name: 'bike1'
# date: '2021/10/2'
condition.id
# ans = 5
Python (dictionary)
condition = {}
condition['id'] = 5
condition['name'] = 'bike1'
condition['date'] = '2021/10/2'
# conditionは{'id': 5, 'name': 'bike1', 'date': '2021/10/2'}
condition['id']
# 5
Python (class)
class Condition:
pass
condition = Condition()
condition.id = 5
condition.name = 'bike1'
condition.date = '2021/10/2'
# condition.__class__.__name__ : "Condition"
condition.id
# 5
Python (namedtuple)
from collections import namedtuple
Condition = namedtuple("Condition", "id name date")
condition = Condition(5, "bike1", '2021/10/2')
# condition: Condition(id=5, name='bike1', date='2021/10/2')
condition.id
# 5
コメント