2009. 7. 1. 19:31
inline함수, 무명함수, 함수포인터 삽질예방/Matlab2009. 7. 1. 19:31
inline 함수( 단점: 수식 안에 파라미터가 아닌 변수 값을 넣을 수 없다)
그리고 feval의 사용법.
>> il_humps = inline('1./((x-.3).^2+.01) + 1./((x-.9).^ + .04) - 6','x');
>> il_humps
il_humps =
Inline function:
il_humps(x) = 1./((x-.3).^2+.01) + 1./((x-.9).^ + .04) - 6
>> il_humps(1)
ans =
-2.9035
>> y = feval('sin', pi*(0:4)/4)
y =
0 0.7071 1.0000 0.7071 0.0000
>> il_humps
il_humps =
Inline function:
il_humps(x) = 1./((x-.3).^2+.01) + 1./((x-.9).^ + .04) - 6
>> il_humps(1)
ans =
-2.9035
>> y = feval('sin', pi*(0:4)/4)
y =
0 0.7071 1.0000 0.7071 0.0000
다음은 무명함수와 함수포인터를 사용하는 예제이다.
function tmpfunc()
clc;
a = 3;
% impossible
% myfunci = inline('sin(x)+a', 'x');
% 무명함수를 정의하고 그것의 포인터를 넘긴다.
myfunc = @(x) sin(x)+a;
myfunc3 = @(x, y) x+y; % 인자가 두개인 경우의 예제
myfunc3(3, 4)
myeval_pointer = @myeval; %% function pointer.
a=0; % this won't change the function of 'myfunc'
% 아래 함수 세개의 결과는 같다
fprintf('myeval=%f\n', myeval(myfunc, 3));
fprintf('feval=%f\n', feval(myfunc, 3));
fprintf('myeval_pointer=%f\n', myeval_pointer(myfunc, 3));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 함수 포인터를 이용하여 이것을 배열에 넣고 사용하기! 매우 편리하겠지???
myfunc2 = @(x) sin(x)+a; % now a is 0
funary = {myfunc, myfunc2};
funary{1}(3)
funary{2}(3)
end
function ret = myeval(func, x)
ret = func(x);
end
clc;
a = 3;
% impossible
% myfunci = inline('sin(x)+a', 'x');
% 무명함수를 정의하고 그것의 포인터를 넘긴다.
myfunc = @(x) sin(x)+a;
myfunc3 = @(x, y) x+y; % 인자가 두개인 경우의 예제
myfunc3(3, 4)
myeval_pointer = @myeval; %% function pointer.
a=0; % this won't change the function of 'myfunc'
% 아래 함수 세개의 결과는 같다
fprintf('myeval=%f\n', myeval(myfunc, 3));
fprintf('feval=%f\n', feval(myfunc, 3));
fprintf('myeval_pointer=%f\n', myeval_pointer(myfunc, 3));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 함수 포인터를 이용하여 이것을 배열에 넣고 사용하기! 매우 편리하겠지???
myfunc2 = @(x) sin(x)+a; % now a is 0
funary = {myfunc, myfunc2};
funary{1}(3)
funary{2}(3)
end
function ret = myeval(func, x)
ret = func(x);
end