[ 선형대수 : matlab ] ch ap 6: 사용자 정의 함수
DESCRIPTION
최 윤 정. [ 선형대수 : Matlab ] Ch ap 6: 사용자 정의 함수. 학습내용. 함수 작성하기 작업 경로 추가하기 (library 경로 지정 ) 익명함수 (anonymous function) 함수의 함수. 6.1 Creating Function M-files. User defined functions are stored as M-files To use them, they must be in the current directory Syntax - PowerPoint PPT PresentationTRANSCRIPT
1
[ 선형대수 :MATLAB]CHAP 6: 사용자 정의 함수
최 윤 정
학습내용
함수 작성하기 작업 경로 추가하기 (library 경로 지정 ) 익명함수 (anonymous function) 함수의 함수
2
3
6.1 Creating Function M-files
User defined functions are stored as M-files
To use them, they must be in the current directory
Syntax
All functions have a similar syntax, whether they are built-in func-
tions or user-defined functions
Name : cos()
Input : X
Result : AA = cos(x)
4
함수를 작성할 때는
함수의 header : function 변수이름 = 함수이름 (argument 로 사용되는 변수이름 )
함수의 이름과 M 화일의 화일명은 반드시 같아야 한다 .
예 ) function output = poly(x)
The function name must be the same as the file name
5
The function is available from the command window or from other M-file programs
함수를 만들면서 중간중간 계산결과들을 명령창에 출력해보며 동작상태를 점검하세요 .
6
함수의 body 에는 code 만 넣지 말고 설명도 넣도록 하세요 .
7
Example 6.1 : degree( 각도 ) radian 변환함수 D2R & R2D 함수
Degree = radian * 180/pi, Radian = degree * pi/180
D2R.m 과 R2D.m 을 만들어 보세요 .
8
결과를 확인합니다 .
9
Functions can accept… Numeric values Variables Scalars Arrays
10
Functions with Multiple Inputs and Outputs
A user defined function with multiple inputs
11
Multiple output : 예 ) max(x)
This function return 3 output values
If you don’t ask for all three results, the program just returns the first value.
스칼라값 세개를 출력한 것처럼 보이지만 실제로는 원소가 3 개인 배열값이 출력됩니다 .
12
Example 6.4 : 운동에너지 달리는 자동차의 운동에너지를 계산하는 KE 함수를 만들어 동작을
확인하세요 . : KE = ½ mv2
입력 :
자동차의 질량 : m (kg)
자동차의 속도 : v (m/s)
출력 : 자동차의 운동에너지 KE (J)
KE.m
No input, No output
13
No output is defined
따라서 , Star 함수를 호출하면서 결과를 할당할 변수를 지정하면 에러 .!
값을 출력하지 않는다고해서 함수가 아무일도 하지 않는 것은 아니다 .
14
Determining the number of input and output arguments
nargin
the number of input arguments
nargout
the number of output arguments
입력의 개수에 대해 융통성있게 만들자 .
Surf() 함수의 nargin 은 -1.!
예 ) surf(z) : 입력이 하나일때 , x,y 는 인덱스 번호로 z 를 그렸고
surf(x,y,z) : x,y 축에 대해 z 를 그린다 .
15
Checks to see how many output values were re-quested
결과를 저장할 변수가 지정되지않았으므로 별만 그린다 .
16
Local variable cf. Global variable
지역변수 :
M 화일에서 사용되는 모든 변수는 지역변수로서 프로그램 파일안에서만 사용할 수 있다 .
명령창에서 X=1 을 입력하여도 함수 화일속에 있는 변수 X 의 값은 1 이 아니다 .
함수화일내에서 y=2 로 정의되어도 작업공간창에서의 변수 y 는 2 가 아니다 .
함수와 명령창 사이에서 데이터를 주고받을 수 있는 유일한 방법은 입력인자와 출력(return) 인자를 통해야 한다 .
전역변수 :
지역변수와 달리 컴퓨터 프로그램 전체에서 사용할 수 있다 .. 그러나 변수를 전역변수로 사용하는 것은 좋지않다 .
17
x, y, a, and output are local variables to the g function
When the g function is executed, the only variable created is determined in the com-mand window (or script M-file used to exe-cute a program)
ans is the only variable created. 함수를 호출해도 x,y,a 는 정의되지않는다 .
18
If you don’t define g in this func-tion, it won’t work!!
19
Accessing M-file Code
사용자 정의함수는 내부코드를 확인할 수 있다 . >> Type star
20
We just wrote this function, and saved it into the current directory.
21
6.2 Creating Your Own Toolbox of Functions
When we call a function MATLAB searches for it along a
predetermined path
First it looks in the current directory
Then it follows a search path determined by your installa-
tion of the program
자신이 만든 함수나 파일을 모아두고 사용하려면 Group them into a directory
Add them to the search path using pathtool
22
검색경로는 - File->setpath - type pathtool in the command window 로 확인한다 .
23
Browse for my folder and add it to the search path
24
6.3 Anonymous Functions
Anonymous functions are defined inside a script M-file,
and are only available to that program
예 ) 자연로그를 계산하는 함수 ln 만들기 ln = @(x)log(x)
@ 기호로 ln 이 함수라는 것을 선언한다 .
@ 다음 함수의 입력을 ( ) 안에 적는다 . (x)
다음 , 정의할 함수를 쓴다 . log(x)
25
function definition
The name of the function is called a func-tion handle – in this case it is ln
26
4.4 Function Functions Some functions accept other functions as input.
함수의 함수 : Fplot() nargin nargout Either syntax gives
the same result
27
함수대신 함수핸들을 넣어도 된다 .
28
Summary Matlab 에는 다양한 내장함수가 들어있다 .
사용자 스스로 필요한 함수를 만들 수도 있다 .
함수이름과 M 파일 이름은 서로 같아야 한다 .
함수를 정의할 때 첫 라인은 : function output = poly(x) Function output_ 변수 = 함수이름 (input 변수 )
M 화일에는 코드 뿐 아니라 설명문도 충분히 사용하도록 하요 help 에 의해 표시되도록 한다 .
사용자 정의함수는 current directory 에 두거나 검색경로에 포함되도록 한다 .
Pathtool 명령과 같은 유용한 도구상자들은 matlab user community 에서 얻을 수 있다 .
29