각 경우 함수의 입력 인수가 다른 것으로 보입니다. 그렇다면 matlab 함수 nargin
이이를 감지 할 수 있으며 추가 method
매개 변수를 지정할 필요가 없습니다. 예를 들어
:
function f = fun(x,y,z)
switch nargin
case 1
f = x.^2; %// run only if ONE argument was specified
case 2
f = fun(x) + y; %// run only if TWO arguments were specified
case 3
f = fun(x,y) ./ z ; %// run only if THREE arguments were specified
otherwise
disp('Houston, we have a problem !!') ; %// run if NO or more than 3 arguments were specified
end
당신은 문제없이 하나 개의 인수, 두 개 또는 세와 f
를 호출 할 수 있습니다, matlab에는 인수의 적절한 번호에 해당하는 기능을 수행합니다.
3 개의 인수와 함께 전달 된 함수는 2 개의 인수 (첫 번째 인수에서 파트를 계산하기 위해 호출 할 수 있음)를 사용하여 파트를 계산할 수 있습니다.
사례 2 : 정말 루프에서 수행 할 수없는 재귀, 고전 if ... then
이 작동됩니다 :
function f = fun(x,y,z)
if nargin == 3
threeArgs = true ;
twoArgs = true ;
elseif nargin == 2
threeArgs = false ;
twoArgs = true ;
elseif nargin == 1
threeArgs = false ;
twoArgs = false ;
end
for it=1:1e6
f = x.^2; %// If method_number==1 run only this command....
%// ... other computations
if twoArgs
f = f + y ; %// If method_number==2 run also this command.
%// ... other computations
if threeArgs
f = f ./z ; %// If method_number==3 run also this command.
%// ... other computations
end
%// ... other computations only relevant to f(x,y)
end
%// ... other computations only relevant to f(x)
end
이 완전히 재귀를 제외 것이며, 연산의 최소 수를 보장합니다.
는 지금이 조금 서투른 코드를 보이는 실현 당신은
if ... then
및
switch
없이 해결책을 요구했다. 계산에 따라
if
또는
switch
을 피할 수있는 방법이 있지만 모든 경우에 실용적이지는 않습니다.
아이디어는 invariant
연산자를 y
또는 z
에 할당하는 것입니다.
예 :
function f = fun(x,y,z)
if nargin < 3 ; z = 1 ; end
if nargin < 2 ; y = 0 ; end
for it=1:1e6
f = x.^2;
%// ... other computations just based on X
f = f + y ; %// This always run, but if "y" wasn't specified, it does not modify the result (f+0=f)
%// ... other computations
f = f ./z ; %// This always run, but if "z" wasn't specified, it does not modify the result (f./1=f)
%// ... other computations
end
이 코드에서 어떤 흐름 분기를 피할 수 있지만, 일부 JIT 컴파일러 될 수 있지만 계산은 항상 (경우에 관계없이 수행되기 때문에 난 단지, 간단한 경우이 방법을 유지할 것 '효과 없음'작업을하지 않아도되는만큼 똑똑한).
[로컬 함수] (http://es.mathworks.com/help/matlab/matlab_prog/local-functions.html) 및 [중첩 함수] (http://es.mathworks.com/ help/matlab/matlab_prog/nested-functions.html) –