Python for MATLAB Users
Justin Kiggins
Product Manager
MATLAB
for i=1:5
disp(i);
end
disp('done');
1
2
3
4
5
done
Python
for i in [1, 2, 3, 4, 5]:
print(i)
print('done')
1
2
3
4
5
done
groceries = ['bread', 'tea', 'banana']
print(groceries)
['bread', 'tea', 'banana']
for item in groceries:
print(item)
bread
tea
banana
abbreviations = {'New York': 'NY',
'California': 'CA',
'Illinois': 'IL',
'Texas': 'TX'}
print(abbreviations)
{'New York': 'NY', 'California': 'CA', 'Illinois': 'IL', 'Texas': 'TX'}
for state, abbv in abbreviations.items():
print(state, abbv)
New York NY
California CA
Illinois IL
Texas TX
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
[1 2 3]
for element in arr:
print(element)
1
2
3
import numpy as np
X = np.array([[1, 2, 3], [4, 5, 6]])
print(X)
[[1 2 3]
[4 5 6]]
for row in X:
print(row)
[1 2 3]
[4 5 6]
import pandas as pd
d = [{'fruit': 'apple', 'color': 'red'},
{'fruit': 'banana', 'color': 'yellow'},
{'fruit': 'pear', 'color': 'green'}]
df = pd.DataFrame(d)
print(df)
color fruit
0 red apple
1 yellow banana
2 green pear
for ii, row in df.iterrows():
print(ii, row['fruit'], row['color'])
0 apple red
1 banana yellow
2 pear green
Python for MATLAB Users