% This m-file is a tutorial on functions clear %% Anonymous' functions % Single function with several inputs sqr = @(x,y) x.^2+y.^2; % lhs is called the 'function handle' sqr(1,2) sqr([1 2], [3 4]) pause % Arrays of function handles S.a = @sin; S.b = @cos; S.c = @tan; S.a(0.3) S.b(0.3) S.c(0.3) %% Can pass function handles as input to other functions f1 = @(x) 0.1*x.^3 - 3*x + 2; fplot(f1,[-5, 5]); grid on; % Plot function x0 = 1; % Starting point for root search root = fzero(f1, x0) % Named function root = fzero(@(x) sin(3*x),2) % Directly pass function definition to another function %% Calling functions help Simpson_rule % display help (all comment lines immediately after function definition line) res=Simpson_rule(@(x) x.^2,[-5 1],100) % Integration by Simpson's rule using anonymous function res=Simpson_rule(@ftest,[0 2],100) % Using standard functions %% Integrating a function with parameters using an anonymous function a=1;b=-2;c=-5; % Define parameters res=Simpson_rule(@(x) ftest2(x,a,b,c),[0 2],100) %% Integrating a function with subfunctions res=Simpson_rule(@ftest3,[0 2],100) %% Difference between nested functions and subfunctions nested_fun % nested functions share variables with outer functions pause bad_subfunction_fun % subfunctions do not share variables with outer functions