SlideShare ist ein Scribd-Unternehmen logo
1 von 25
PyCon Korea 2019
MATLAB 사용자에서 Python 사용자로 거듭나기
광고시간
• 서비스 : 자동차 견인/출동 서비스 ‘원더카’
• 커넥티드카 서비스 플랫폼 '오스카’, LBS 기반 모바일 플랫폼 '코스모스'
자동차를 좋아하는 사람들이
자동차에 필요한 개발을 하는 회사
• Python을 사용하게 된 계기
• 닮은 점과 다른 점 비교
• MATLAB으로 하던 일을 Python으로 대체하기
• Numpy, Scipy 등을 활용한 대체
• Python이 대체하기 힘든 부분
• Python이 MATLAB보다 좋은 부분
내용
• 대학교, 기관에서 많이 사용
• 검증된 코드, 관리되는 코드
• MATLAB의 결과는 신뢰를 보장함
http://blog.naver.com/PostView.nhn?blogId=matlablove&logNo=221104783201&categoryNo=1&parent
CategoryNo=-1&viewDate=&currentPage=&postListTopCurrentPage=&isAfterWrite=true
신뢰의 MATLAB
help 함수명
• 대학교에서
• 그래프를 이쁘게 그려보자
• 행렬 계산
• 첫 직장에서
• 시각화
• 데이터 분석 및 처리
어쩌다가 MATLAB을
어쩌다가 Python을
MATLAB과 비슷한 개발 환경을 제공하는 Anaconda
라이센스 문제가 없음
• 닮은 점
• (수학이나 공학에서)비슷한 일을 할 수 있음
• 시각화(matplotlib)
• 특정 함수들(scipy)
• 다른 점
• MATLAB: 더 수학적, Python: 더 프로그래밍 언어적
• Python은 오픈소스(공짜), MATLAB은 상용 소프트웨어 패키지(유료)
a * b
?
MATLAB vs Python
MATLAB vs Python
MALTAB 중추
- IDE
- 인터프리터(interpreter)
- 언어
- (방대한)기본 라이브러리
- GUI 만드는 거
Simulink
Image processing 툴킷
기타 툴킷
FileExchange
Python 중추
- 인터프리터(interpreter)
- 언어
- 기본 라이브러리
Numpy
Matplotlib
Scipy
PyQt5
기타 라이브러리
Scikit-image
여러 IDE
- PyCharm
- Spyder
- VisualStudio
Code
- 기타 등등
MATLAB 환경 Python 환경
닮았어요
MATLAB 기본 IDE Spyder (Anaconda)
script scriptconsole console
variable
variable
MATLAB 처럼 메모리 관리
Ipython : %reset 혹은
close all
clear
clc
del x
print('n'*100)
import os
cls = lambda: os.system('cls’)
cls()
for name in dir():
if not name.startswith('_’):
del globals()[name]
MATLAB에서
스크립트의 시작을 알리는 관용구
jupyter notebook에서 : Kernel > Restart
%reset %reset -f
별거 아닌 듯 가장 큰 차이
a = 1:1:10;
a(4:2:8);
a = arange(1,10,1)
a[3:8:2]
• Element index 쓰는 법이 약간 다름
• ()를 []로
• 1부터 시작, 0부터 시작
• end , -1
a[:] = 5a(:) = 5
a(1,2) a[0,1]
a[0:3][:,4:10]a(1:3,5:10)
from numpy import *
import scipy.linalg
Numpy로 MATLAB 처럼
disp(a) print(a)
spacing()eps()
1 and 1
0 or 00 || 0
1 && 1
max(a) a.max(0)
linspace(1,5,10)linspace(1,5,10)
[ 1 2 3; 4 5 6 ] array([[1.,2.,3.], [4.,5.,6.]])
nonzero(a>4)find(a>4)
이름이 전혀 다른데?
https://kr.mathworks.com/help/matlab/ref/ind2sub.html
선형 index를 반환 위치기준 index를 반환
find() nonzero()
비슷한데 뭔가 달라
특정 matrix에서 최대값
• 각 행에서 최대값
• 각 열에서 최대값
• 전체 매트릭스에서 최대값
max(a) a.max(0)
행렬을 많이 다루다 보면
a * b a @ b
a .* b a * b
a ./ b a / b
a' a.conj().transpose()
a.conj().T
a.' a.transpose()
a.T
squeeze(a) a.squeeze()
repmat(a, m, n) tile(a, (m, n))
linalg.solve(a,b)
linalg.lstsq(a,b)
unique(a)
fft(a)fft(a)
ifft(a) ifft(a)
diag(a) diag(a)
eye(3)eye(3)
linspace(1,5,10)linspace(1,5,10)
sort(a)sort(a)
unique(a)
zeros((3,4))zeros(3,4)
ones(3,4) ones((3,4))
flipud(a)flipud(a)
fliplr(a) fliplr(a)
사실 거의 같아요
x, y = meshgrid([1,2,3],[4,5,6])[x, y] = meshgrid([1,2,3],[4,5,6])
MATLAB .mat 파일
import scipy.io
mat = scipy.io.loadmat('a.mat')
mat['a']
Python에서 ‘.mat’ 파일은
기본적으로 dict로
A = {"name" : "홍길동", "age“ : 20}
MATLAB .mat structure파일
MATLAB structure array dict 하부에 list로 존재함
https://kr.mathworks.com/help/matlab/ex
amples/create-a-structure-array.html
시각화
x = arange(0.0, 2.0*pi, pi/100)
y = sin(x)
plot(x, y)
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
from numpy import *
import scipy.linalg
from matplotlib.pyplot import *
보통 Python에서는
x = np.arange(0.0, 2.0*np.pi, np.pi/100)
y = np.sin(x)
plt.plot(x, y)
MATLAB에서는
기본 라이브러리가 매우 방대함
plt.show()hold on ≒
axis([0,1,-1.5,1.5])axis([0 1 -1.5 1.5])
MATLAB vs matplotlib
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y);
xlabel('Location’);
ylabel('y’);
xticks([0 2 4 6]);
xticklabels({'x=0','x=2','x=4','x=6'});
text(pi,0,'< here’)
grid()
title('Test Plot’)
legend('loc','Location','northeast')
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2.0*np.pi, np.pi/100)
y = np.sin(x)
plot1 = plt.plot(x, y)
plt.xlabel('Location’)
plt.ylabel('y’)
plt.xticks([0,2,4,6],['x=0','x=2','x=4','x=6’])
plt.text(np.pi,0, '< here’)
plt.grid()
plt.title('Test Plot’)
plt.legend(plot1, ['loc'], loc='upper right’)
plt.show()
Python에는 더 많은 시각화 라이브러리가 존재
More interactive plot : plotly, bokeh
scatter()plot3() bar()
contour()pie() surf() hist() polar()
Deprecated!
• Sympy :
• Jupyter notebok에서 출력되는 결과물이 mathjax(javascript)로 나옴
Symbolic Mathematics in Python
pip install sympy
http://scipy-lectures.org/packages/sympy.html
https://www.sympy.org/en/index.html
다항식 전개 인수분해
극한
미분, 적분
행렬 방정식 풀이
• Simulink
• 초심자가 시작하기에 더 좋음
• 검증된 코드(검증된 신뢰성)
• 임베디드 코드 생성, 이식가능한 C/C++ 코드를 생성함
• 기술지원
• 속도
Python이 대체하기 힘든 부분
정말 Python은 MATLAB 보다 느릴까?
from numba import jit
import random
@jit(nopython=True)
def monte_carlo_pi(nsamples):
acc = 0
for i in range(nsamples):
x = random.random()
y = random.random()
if (x ** 2 + y ** 2) < 1.0:
acc += 1
return 4.0 * acc / nsamples
Decorator 하나만 붙여주면 그냥 속도가 빨라짐
• 최신 버전의 Python을 사용하면 빠르다(3.7)
• Cython
• Async I/O
https://www.ibm.com/developerworks/communit
y/blogs/jfp/entry/A_Comparison_Of_C_Julia_Pyt
hon_Numba_Cython_Scipy_and_BLAS_on_LU_
Factorization?lang=en
https://numba.pydata.org/
• 나의 MATLAB 수준, Python수준, 수학 수준
• 뭐요? Import MATLAB 이요?? MATLAB API
• MATLAB or Python translator
• Python을 위한 Simulink, Block-Model Simulator(bms)
• R? Julia?
준비하면서 알게된 점
• 여기에 다 적지 못해서 이만 발표를 마치겠습니다.
Python이 MATLAB보다 좋은 부분

Weitere ähnliche Inhalte

Was ist angesagt?

Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02Seok-joon Yun
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07Seok-joon Yun
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
TenforFlow Internals
TenforFlow InternalsTenforFlow Internals
TenforFlow InternalsKiho Hong
 
13장 연산자 오버로딩
13장 연산자 오버로딩13장 연산자 오버로딩
13장 연산자 오버로딩유석 남
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)fmbvbfhs
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기지수 윤
 
From MATLAB User to Python User
From MATLAB User to Python UserFrom MATLAB User to Python User
From MATLAB User to Python UserIntae Cho
 
RNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifRNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifitlockit
 
Deferred Shading
Deferred ShadingDeferred Shading
Deferred Shading종빈 오
 
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )Gunhee Lee
 
종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍Kwang Yul Seo
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814Jaewook. Kang
 
2.linear regression and logistic regression
2.linear regression and logistic regression2.linear regression and logistic regression
2.linear regression and logistic regressionHaesun Park
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법Terry Cho
 

Was ist angesagt? (20)

Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02
 
1. alps c&c++
1. alps c&c++1. alps c&c++
1. alps c&c++
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07
 
6 swift 고급함수
6 swift 고급함수6 swift 고급함수
6 swift 고급함수
 
A tour of go
A tour of goA tour of go
A tour of go
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
TenforFlow Internals
TenforFlow InternalsTenforFlow Internals
TenforFlow Internals
 
13장 연산자 오버로딩
13장 연산자 오버로딩13장 연산자 오버로딩
13장 연산자 오버로딩
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기
 
From MATLAB User to Python User
From MATLAB User to Python UserFrom MATLAB User to Python User
From MATLAB User to Python User
 
iOS 메모리관리
iOS 메모리관리iOS 메모리관리
iOS 메모리관리
 
RNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifRNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, if
 
Deferred Shading
Deferred ShadingDeferred Shading
Deferred Shading
 
5. queue
5. queue5. queue
5. queue
 
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
 
종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814
 
2.linear regression and logistic regression
2.linear regression and logistic regression2.linear regression and logistic regression
2.linear regression and logistic regression
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법
 

Ähnlich wie Pyconkr2019 features for using python like matlab

[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
 
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)Tae Young Lee
 
웃으면서Python
웃으면서Python웃으면서Python
웃으면서PythonJiyoon Kim
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차Han Sung Kim
 
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로Oracle Korea
 
[A1]루비는 패셔니스타
[A1]루비는 패셔니스타[A1]루비는 패셔니스타
[A1]루비는 패셔니스타NAVER D2
 
Alphago at a Glance
Alphago at a GlanceAlphago at a Glance
Alphago at a GlanceDataya Nolja
 
DEVIEW-FULL-감독판.pptx
DEVIEW-FULL-감독판.pptxDEVIEW-FULL-감독판.pptx
DEVIEW-FULL-감독판.pptxhanbeom Park
 
Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀beom kyun choi
 
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) Tae Young Lee
 
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Senchamniktw
 
Python programming for Bioinformatics
Python programming for BioinformaticsPython programming for Bioinformatics
Python programming for BioinformaticsHyungyong Kim
 
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작Taeyoung Kim
 
introduce of Hadoop map reduce
introduce of Hadoop map reduceintroduce of Hadoop map reduce
introduce of Hadoop map reduceDaeyong Shin
 
3.neural networks
3.neural networks3.neural networks
3.neural networksHaesun Park
 

Ähnlich wie Pyconkr2019 features for using python like matlab (20)

[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
파이썬 데이터과학 레벨2 - 데이터 시각화와 실전 데이터분석, 그리고 머신러닝 입문 (2020년 이태영)
 
파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)파이썬 데이터 분석 (18년)
파이썬 데이터 분석 (18년)
 
웃으면서Python
웃으면서Python웃으면서Python
웃으면서Python
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차
 
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
 
Java.next
Java.nextJava.next
Java.next
 
[A1]루비는 패셔니스타
[A1]루비는 패셔니스타[A1]루비는 패셔니스타
[A1]루비는 패셔니스타
 
Alphago at a Glance
Alphago at a GlanceAlphago at a Glance
Alphago at a Glance
 
DEVIEW-FULL-감독판.pptx
DEVIEW-FULL-감독판.pptxDEVIEW-FULL-감독판.pptx
DEVIEW-FULL-감독판.pptx
 
Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀
 
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
 
Just java
Just javaJust java
Just java
 
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
 
Python programming for Bioinformatics
Python programming for BioinformaticsPython programming for Bioinformatics
Python programming for Bioinformatics
 
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작
//BUILD/ Seoul - .NET의 현재와 미래. 그 새로운 시작
 
introduce of Hadoop map reduce
introduce of Hadoop map reduceintroduce of Hadoop map reduce
introduce of Hadoop map reduce
 
파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝
 
3.neural networks
3.neural networks3.neural networks
3.neural networks
 

Pyconkr2019 features for using python like matlab

  • 1. PyCon Korea 2019 MATLAB 사용자에서 Python 사용자로 거듭나기
  • 2. 광고시간 • 서비스 : 자동차 견인/출동 서비스 ‘원더카’ • 커넥티드카 서비스 플랫폼 '오스카’, LBS 기반 모바일 플랫폼 '코스모스' 자동차를 좋아하는 사람들이 자동차에 필요한 개발을 하는 회사
  • 3. • Python을 사용하게 된 계기 • 닮은 점과 다른 점 비교 • MATLAB으로 하던 일을 Python으로 대체하기 • Numpy, Scipy 등을 활용한 대체 • Python이 대체하기 힘든 부분 • Python이 MATLAB보다 좋은 부분 내용
  • 4. • 대학교, 기관에서 많이 사용 • 검증된 코드, 관리되는 코드 • MATLAB의 결과는 신뢰를 보장함 http://blog.naver.com/PostView.nhn?blogId=matlablove&logNo=221104783201&categoryNo=1&parent CategoryNo=-1&viewDate=&currentPage=&postListTopCurrentPage=&isAfterWrite=true 신뢰의 MATLAB help 함수명
  • 5. • 대학교에서 • 그래프를 이쁘게 그려보자 • 행렬 계산 • 첫 직장에서 • 시각화 • 데이터 분석 및 처리 어쩌다가 MATLAB을
  • 6. 어쩌다가 Python을 MATLAB과 비슷한 개발 환경을 제공하는 Anaconda 라이센스 문제가 없음
  • 7. • 닮은 점 • (수학이나 공학에서)비슷한 일을 할 수 있음 • 시각화(matplotlib) • 특정 함수들(scipy) • 다른 점 • MATLAB: 더 수학적, Python: 더 프로그래밍 언어적 • Python은 오픈소스(공짜), MATLAB은 상용 소프트웨어 패키지(유료) a * b ? MATLAB vs Python
  • 8. MATLAB vs Python MALTAB 중추 - IDE - 인터프리터(interpreter) - 언어 - (방대한)기본 라이브러리 - GUI 만드는 거 Simulink Image processing 툴킷 기타 툴킷 FileExchange Python 중추 - 인터프리터(interpreter) - 언어 - 기본 라이브러리 Numpy Matplotlib Scipy PyQt5 기타 라이브러리 Scikit-image 여러 IDE - PyCharm - Spyder - VisualStudio Code - 기타 등등 MATLAB 환경 Python 환경
  • 9. 닮았어요 MATLAB 기본 IDE Spyder (Anaconda) script scriptconsole console variable variable
  • 10. MATLAB 처럼 메모리 관리 Ipython : %reset 혹은 close all clear clc del x print('n'*100) import os cls = lambda: os.system('cls’) cls() for name in dir(): if not name.startswith('_’): del globals()[name] MATLAB에서 스크립트의 시작을 알리는 관용구 jupyter notebook에서 : Kernel > Restart %reset %reset -f
  • 11. 별거 아닌 듯 가장 큰 차이 a = 1:1:10; a(4:2:8); a = arange(1,10,1) a[3:8:2] • Element index 쓰는 법이 약간 다름 • ()를 []로 • 1부터 시작, 0부터 시작 • end , -1 a[:] = 5a(:) = 5 a(1,2) a[0,1] a[0:3][:,4:10]a(1:3,5:10) from numpy import * import scipy.linalg
  • 12. Numpy로 MATLAB 처럼 disp(a) print(a) spacing()eps() 1 and 1 0 or 00 || 0 1 && 1 max(a) a.max(0) linspace(1,5,10)linspace(1,5,10) [ 1 2 3; 4 5 6 ] array([[1.,2.,3.], [4.,5.,6.]]) nonzero(a>4)find(a>4)
  • 13. 이름이 전혀 다른데? https://kr.mathworks.com/help/matlab/ref/ind2sub.html 선형 index를 반환 위치기준 index를 반환 find() nonzero()
  • 14. 비슷한데 뭔가 달라 특정 matrix에서 최대값 • 각 행에서 최대값 • 각 열에서 최대값 • 전체 매트릭스에서 최대값 max(a) a.max(0)
  • 15. 행렬을 많이 다루다 보면 a * b a @ b a .* b a * b a ./ b a / b a' a.conj().transpose() a.conj().T a.' a.transpose() a.T squeeze(a) a.squeeze() repmat(a, m, n) tile(a, (m, n)) linalg.solve(a,b) linalg.lstsq(a,b)
  • 16. unique(a) fft(a)fft(a) ifft(a) ifft(a) diag(a) diag(a) eye(3)eye(3) linspace(1,5,10)linspace(1,5,10) sort(a)sort(a) unique(a) zeros((3,4))zeros(3,4) ones(3,4) ones((3,4)) flipud(a)flipud(a) fliplr(a) fliplr(a) 사실 거의 같아요 x, y = meshgrid([1,2,3],[4,5,6])[x, y] = meshgrid([1,2,3],[4,5,6])
  • 17. MATLAB .mat 파일 import scipy.io mat = scipy.io.loadmat('a.mat') mat['a'] Python에서 ‘.mat’ 파일은 기본적으로 dict로 A = {"name" : "홍길동", "age“ : 20}
  • 18. MATLAB .mat structure파일 MATLAB structure array dict 하부에 list로 존재함 https://kr.mathworks.com/help/matlab/ex amples/create-a-structure-array.html
  • 19. 시각화 x = arange(0.0, 2.0*pi, pi/100) y = sin(x) plot(x, y) x = 0:pi/100:2*pi; y = sin(x); plot(x,y) from numpy import * import scipy.linalg from matplotlib.pyplot import * 보통 Python에서는 x = np.arange(0.0, 2.0*np.pi, np.pi/100) y = np.sin(x) plt.plot(x, y) MATLAB에서는 기본 라이브러리가 매우 방대함 plt.show()hold on ≒ axis([0,1,-1.5,1.5])axis([0 1 -1.5 1.5])
  • 20. MATLAB vs matplotlib x = 0:pi/100:2*pi; y = sin(x); plot(x,y); xlabel('Location’); ylabel('y’); xticks([0 2 4 6]); xticklabels({'x=0','x=2','x=4','x=6'}); text(pi,0,'< here’) grid() title('Test Plot’) legend('loc','Location','northeast') import matplotlib.pyplot as plt import numpy as np x = np.arange(0.0, 2.0*np.pi, np.pi/100) y = np.sin(x) plot1 = plt.plot(x, y) plt.xlabel('Location’) plt.ylabel('y’) plt.xticks([0,2,4,6],['x=0','x=2','x=4','x=6’]) plt.text(np.pi,0, '< here’) plt.grid() plt.title('Test Plot’) plt.legend(plot1, ['loc'], loc='upper right’) plt.show() Python에는 더 많은 시각화 라이브러리가 존재 More interactive plot : plotly, bokeh scatter()plot3() bar() contour()pie() surf() hist() polar() Deprecated!
  • 21. • Sympy : • Jupyter notebok에서 출력되는 결과물이 mathjax(javascript)로 나옴 Symbolic Mathematics in Python pip install sympy http://scipy-lectures.org/packages/sympy.html https://www.sympy.org/en/index.html 다항식 전개 인수분해 극한 미분, 적분 행렬 방정식 풀이
  • 22. • Simulink • 초심자가 시작하기에 더 좋음 • 검증된 코드(검증된 신뢰성) • 임베디드 코드 생성, 이식가능한 C/C++ 코드를 생성함 • 기술지원 • 속도 Python이 대체하기 힘든 부분
  • 23. 정말 Python은 MATLAB 보다 느릴까? from numba import jit import random @jit(nopython=True) def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples Decorator 하나만 붙여주면 그냥 속도가 빨라짐 • 최신 버전의 Python을 사용하면 빠르다(3.7) • Cython • Async I/O https://www.ibm.com/developerworks/communit y/blogs/jfp/entry/A_Comparison_Of_C_Julia_Pyt hon_Numba_Cython_Scipy_and_BLAS_on_LU_ Factorization?lang=en https://numba.pydata.org/
  • 24. • 나의 MATLAB 수준, Python수준, 수학 수준 • 뭐요? Import MATLAB 이요?? MATLAB API • MATLAB or Python translator • Python을 위한 Simulink, Block-Model Simulator(bms) • R? Julia? 준비하면서 알게된 점
  • 25. • 여기에 다 적지 못해서 이만 발표를 마치겠습니다. Python이 MATLAB보다 좋은 부분