1) Local variable of function
variables generated in main program are stored in workspace
variables generated in function disappear when function is over
clear
a = 20
b = 30
y = fn_local(3)
whos
* function이 끝나면 바깥 세상에서는 사라진다
2) Global variable of function ("official" IO channel for function)
function [ out1, out2, ... ] = fn_name( in1, in2, ...)
----------------
----------------
global variable → allows "unofficial" IO channel for function
type fn_global
z = fn_global(3,5) % 여기까지 실행하면 z = []로 나옴. A B C를 안줬기 때문
global A B C % do not use comma to define multiple global vars
A = 7, B = 3, C = 5
z = fn_global(3,5)
A
who global % global vars만 보여줌
clear global % global vars 삭제, clear로 삭제해도 fn_global(2,3)을 입력했을 때 값이 보이는 이유는
% base workspace에서는 삭제되었지만 global workspace에서는 살아있기 때문. 따라서 clear global 해야 완전 삭제.
3) Function handle (어떤 함수의 이름이다)
try :
y = cos(3)
a = 'cos'
y = a(3) % ans = 's'. is this same as y = cos(3)?
* fhandle & feval *
a = @cos % function handle
whos a
y = a(3) % same as y = cos(3)
y = feval(a,3) % The feval function follows the same scoping and precedence rules as calling a function handle directly.
4) Exercise : function handles
function can take function names as input
let's change main_func1 into a function (fn_func1)
input : x0 (initial guess), function names
output : x (solution), i (# of iterations)
[x, i] = fn_func1(x0,fn)
Conflict of Names
5) conflict b/w names of
% 우선순위 (matlab은 이름 가지고 구분을 못한다)
variables
commands/functions
files (both Matlab & Simulink)
rand = 13; % built-in function인데, 우리가 변수로 설정해버리면 망함. rand(1,3) 안됨.
clear rand % 변수로 설정했을때 지워주는 명령.
main_func1 = 4; %file
clear main_func1
6) precedence among names
variables
files in the directories specified by MATLAB's search path