radiation imaging lab ta: 윤한빈bml.pusan.ac.kr/resources/intromatlab.pdfmarch 14, 2012 radiation...
Post on 13-Feb-2020
0 Views
Preview:
TRANSCRIPT
March 14, 2012
Radiation imaging lab 실습 TA: 윤한빈
Hanbean.youn@gmail.com
Introduction to MATLAB
실습: 매트랩 기초
12년 3월 21일 수
Outline• 이번시간에는 ...
• 간략한 소개
• 행렬 연산
• 함수, 변수, 사용법
• Built-in functions
• M-files
• Graph
12년 3월 21일 수
Textbook
“Applied Numerical Methods with MATLAB for Engineers and Scientists (2 ed.)”Steven C. Chapra
McGRAW-HILL international edition
12년 3월 21일 수
Introduction
12년 3월 21일 수
문제의 풀이
Z 2
1xdx =
x
2
2
����2
1
= 2� 0.5 = 1.5해석적 풀이
수치해석적 풀이
Z 2
1xdx = lim
n!1
nX
k=1
xk�x
= 1⇥ 0.1 + 1.1⇥ 0.1 + 1.2⇥ 0.1 + . . .
⇡ 1.5
12년 3월 21일 수
Why numerical analysis?
12년 3월 21일 수
Why numerical analysis?
12년 3월 21일 수
Introduction to MATLAB
12년 3월 21일 수
MATLAB• MATLAB(매틀랩)은 MathWorks 사에서 개발한 수치해석 및 프로그래밍 환경을 제공하는 공학용 소프트웨어 이다. 행렬을 기반으로 한 계산 기능을 지원하며, 함수나 데이터를 그림으로 그리는 기능 및 프로그래밍을 통한 알고리즘 구현 등을 제공한다. MATLAB은 수치 계산이 필요한 과학 및 공학 분야에서 다양하게 사용된다. (Wikipedia.org)
• 매틀랩은 Mathworks에서 개발한 공학용 계산 도구 이다.
• MATLAB 이용범위
• 복잡한 공학적 문제의 모델링 및 해 도출
• 수학적인 계산 (행렬연산에 특화)
• 알고리즘 개발 (text coding, graphical coding)
• 상황 모델링과 데이터 분석
• 여러 가지 과학과 공학적인 그래프 표현
• GUI를 채택한 application 개발
12년 3월 21일 수
MATLAB• MATLAB (MATrix LABoratory)
WorkspaceEditor (m-file)
Command window12년 3월 21일 수
Which one is better?
VS.
12년 3월 21일 수
Which one is better?
12년 3월 21일 수
프로그래밍 ...
12년 3월 21일 수
프로그래밍 ...
12년 3월 21일 수
When you have any questions...
12년 3월 21일 수
When you have any questions...
• 윤한빈• http://bml.pusan.ac.kr
• been@pusan.ac.kr
• 051-510-3921
• 010-4567-9371
• 기계관 3301호
12년 3월 21일 수
Matrix• Matlab은 Matrix laboratory의 약자이다.
• 따라서 Matlab은 행렬 연산에 최적화 되어 있다.
• Matlab을 사용할때는 행렬연산을 이용하면 최적의 연산을 수행할 수 있다.
• 연산을 할때 행렬 형태로 만들어서 하자!! (안될때는 어쩔수 없다. 그냥 하자)
12년 3월 21일 수
§행 – 띄어쓰기, 쉼표로 구분
§열 – 세미콜론, 엔터로 구분
>>A=[1, 2, 3; 4 5 6 7 8, 8]
A=1 2 3 4 5 67 8 8
§ Matrix subscriptsA(i,j): the element in raw i and column j
A(1,2) = 2A(2,3) = 6
§ sum: the sum of matrix in one direction>>sum(A)12 15 17>>sum(sum(A))44
§ Transpose (AT=A’)>>A’1 4 72 5 83 6 8
§ diag: picks off the diagonal of A>>diag(A)158
Matrix
12년 3월 21일 수
§ + addition§ - substraction§ * multiplication§ / right division§ \ left division§ ^ power§ ’ transpose
§ Colon operation (:) start : increment : endEx]>> 1:101 2 3 4 5 6 7 8 9 10>> 1:2:101 3 5 7 9>> A(:,2)+3 à???
§ Dot operation (.) component calculation>>A^230 36 3966 81 9095 118 133
>>A.^21 4 916 25 3649 64 64
Operation
12년 3월 21일 수
§변수명 (variable) = 수식 (expression)•변수: int16, int32, double, char, struct, cell 등•수식: MATLAB이 해석할 수 있는 numerical, nonnumerical 수식•MATLAB은 별도의 변수형에 대한 정의는 필요 없음
§변수와 함수는 정확히 구분할 것• variable=function(input_variable);•여기서 function은 MATLAB 내장 함수 혹은 사용자 정의 함수
§A= a (정수) + b (실수)§결과 A à 실수
Statements, expressions and variables
a=1;b=2;c=a+b;
12년 3월 21일 수
§ eye - identity matrix§ zeros - matrix of zeros (variable initialization)§ ones - matrix of ones§ diag - see below§ triu - upper triangular part of a matrix§ tril - lower triangular part of a matrix§ rand - randomly generated matrix§ hilb - Hilbert matrix§ magic - magic square
Matrix building function
12년 3월 21일 수
§ if
if relation statementselseif relation statementselse relation statementsend
§while
while relation statementsend
§ switch
switch reference case value1 statements case value2 statements otherwise statementsend
§ for (computing cost)
for index=start:increment:end statementsend
Structure statements (if, switch, while , for)
팁: for, if문만 알고 있으면 대부분의 계산을 할 수 있다.
12년 3월 21일 수
§sin§cos§ tan§asin§acos§atan§sinh§cosh§ tanh§exp§ log (natural log)§rem (remainder)§abs§sqrt§sign§round§ floor
§max§min§sum§median§any§prod§mean§all§sort§std
Built-in functions
12년 3월 21일 수
§eig eigenvalues and eigenvectors§chol Cholesky factorization§svd singular value decomposition§ inv inverse matrix§ lu LU factorization§qr QR factorization§hess hessenberg form§schur schur decomposition§ rref reduced row echelon form§expm matrix exponential§sqrtm matrix square root§poly characteristic polynomial§det determinant§size size§norm 1-norm, 2-norm, F-norm, infinity norm§cond condition number in the 2-norm§ rank rank
Built-in functions
12년 3월 21일 수
• 2*2 역행렬을 구해보자 • 1부터 10까지 모든 수의 합을 구해보자
실습
12년 3월 21일 수
• 먼저 매트랩을 설치하고
• 많이 써보아야 한다.
매트랩을 잘 하는법?
12년 3월 21일 수
• 끝
12년 3월 21일 수
March 21, 2012
Radiation imaging lab 실습 TA: 윤한빈
Hanbean.youn@gmail.com
Introduction to MATLAB
실습: 매트랩 기초 2
12년 3월 21일 수
Outline• 간략한 소개
• 행렬 연산
• 함수, 변수, 사용법
• Built-in functions
• 이번시간에는 ...
• M-files
• Graph
• 실습
12년 3월 21일 수
• Matrix inversion (manual and built-in function)• Calculate sum from 1 to 10
Review
12년 3월 21일 수
• MATLAB 언어로 쓰여진 파일• Script mode: 연속된 MATLAB 명령어 (command window 동일)• Function mode: 입/출력 매개변수 사용 (m-file 자체가 하나의 함수로 사용)
M-file editorM-file generation
M-files
12년 3월 21일 수
§A script file consists of a sequence of normal MATLAB statements
clear all;t= -pi : pi/100 : pi;y= sin(t);plot(t,y)xlabel(‘t [rad]’)ylabel(‘sin(t)’)
axis ([ -3 3 -1.2 1.2])
axis([x_min x_max y_min y_max])
M-file (script mode)
12년 3월 21일 수
§ Function files provide extensibility to MATLAB§You can create new functions specific to your problem which will then have the same status as
other MATLAB functions
function [mean, stdev]=stat(x)% STAT Mean and standard deviation% For a vector x, stst(x) returns the% mean and standard deviation of x.% For a matrix x, stst(x) returns two row% vectors containing, respectively, the% mean and standard deviation of each column[m n]=size(x);if m==1 m=nendmean=sum(x)/m;stdev=sqrt(sum(x.^2)/m-mean.^2);
function & file name
output
M-file (function)
12년 3월 21일 수
>> s = ‘This is a test’s= This is a test
>> disp(‘this message is hereby displayed’) or fprintf(‘this message is hereby displayed\n’)this message is hereby displayed
>> error(‘Sorry, the matrix must be symmetric’)??? Sorry, the matrix must be symmetric
>> iter= input(‘Enter the number of iteration: ’)Enter the number of iteration: 13iter=13
Strings, error messages and input
12년 3월 21일 수
§ format short fixed point with 4 decimal places (default) A=1.7374
§ format long fixed point with 14 decimal places A=1.737635236326245
Output format
12년 3월 21일 수
§ plot.m 함수 사용법
>> X=[1:10; 0.7*[1:10]; 0.5*[1:10]; 0.25*[1:10]]';>> plot(X,'LineWidth',5);>> xlabel('x axis','fontsize',15)>> ylabel('y axis','fontsize',15)>> title('plot.m 함수 이용법','fontsize',15)
>> grid on;Color à default
Grid
Graph
12년 3월 21일 수
§ subplot.m 함수 사용법 à subplot(m, n, p)
>> t=0:1/100:20;>> y=sin(t);>> subplot(2,2,1);>> plot(t,y);>> z=cos(2*t);>> subplot(2,2,2);>> plot(t,z);>> x=exp(-t);>> subplot(2,2,3);>> plot(t,x);>> w=exp(-sin(t));>> subplot(2,2,4);>> plot(t,w);
Graph
12년 3월 21일 수
§ hold on; off;
>> t=0:1/1000:4;>> x=exp(-t);>> plot(t,x,'LineWidth',3);
>> hold on;
>> y=sin(t);>> plot(t,y,'r','LineWidth',3);
>> hold off;
>> figure,plot(t,y); ß ?
Graph
12년 3월 21일 수
1. Graph 그리기
- Sine 함수 [0:0.01:3.14], [0:1:360]
- Gauss 함수 1D, 2D
2. Image display
3. Function coding
실습
12년 3월 21일 수
§clear all;§close all;§fclose all;§clc §Ctrl+C on command window
§좌측 하단 Start à Preference
§m-file 저장이름 첫 자리 숫자 불가, 기존 내장함수와 같은 이름 불가§m-file 실행 시 current folder 위치 (version에 따라 다름)
Tip
12년 3월 21일 수
§ MATLAB application examples
12년 3월 21일 수
top related