← MATLAB EnglishChapter 05 of 13

Functions

## Learning Objectives - Understand script vs function files - Create and call functions - Pass parameters and return values - Work with anonymous functions - Handle variable argument lists ## Scripts vs Functions ### Scripts - Saved in `.m` files with commands - Operate on variables in the workspace - No input/output arguments ```matlab % myscript.m a = 5; b = 10; c = a + b; disp(c); ``` ### Script vs Function - Accept inputs and return outputs - Have their own workspace - Encapsulate reusable code ```matlab % myfunction.m function output = myfunction(input) output = input * 2; end ``` ## Function File Structure ### Basic Function ```matlab function output = square(x) %SQUARE Returns the square of a number % square(x) computes x^2 output = x ^ 2; end ``` ### Multiple Inputs and Outputs ```matlab function [sum, product] = calc(x, y) %CALC Computes sum and product % [s, p] = calc(x, y) returns sum s and product p sum = x + y; product = x * y; end ``` ### Function with No Output ```matlab function printMessage(msg) %PRINTMESSAGE Displays a message disp(msg); end ``` ## Calling Functions ### Basic Call ```matlab % Single output result = square(5); disp(result); % 25 % Multiple outputs [s, p] = calc(3, 4); disp(s); % 7 disp(p); % 12 ``` ### Pass by Value ```matlab % MATLAB uses pass-by-value for most types function y = double(x) x = x * 2; y = x; end a = 5; b = double(a); disp(a); % 5 (unchanged) disp(b); % 10 ``` ## Anonymous Functions ### Basic Anonymous Function ```matlab % Syntax: @(args) expression sqr = @(x) x ^ 2; result = sqr(5); % 25 % Multiple inputs add = @(x, y) x + y; result = add(3, 4); % 7 ``` ### Using Anonymous Functions ```matlab % As function arguments arr = [1, 2, 3, 4, 5]; result = arrayfun(@(x) x^2, arr); % Create function handles f = @(x) sin(x) / x; f(0) % Returns 1 (limit) ``` ### Returning Multiple Values ```matlab % Using cell arrays stats = @(x) {mean(x), std(x)}; result = stats([1, 2, 3, 4, 5]); meanVal = result{1}; % 3 stdVal = result{2}; % 1.5811 ``` ## Variable Arguments ### Variable Number of Inputs ```matlab function result = sumAll(varargin) %SUMALL Sums all input arguments result = 0; for i = 1:length(varargin) result = result + varargin{i}; end end sumAll(1, 2, 3) % 6 sumAll(1, 2, 3, 4) % 10 ``` ### Variable Number of Outputs ```matlab function varargout = powers(x, n) %POWERS Returns powers of x from 1 to n for i = 1:n varargout{i} = x ^ i; end end [a, b, c] = powers(2, 3); % a=2, b=4, c=8 ``` ## Nested Functions ### Nested Function Scope ```matlab function outerFunction(x, y) %OUTERFUNCTION Outer function z = 10; function innerFunction(a) %INNERFUNCTION Nested function % Can access x, y, z from outer scope result = a + x + y + z; disp(result); end innerFunction(5); end ``` ### Shared Variables ```matlab function mainFunction() shared = 0; function increment() % Can modify shared variable shared = shared + 1; end increment(); increment(); disp(shared); % 2 end ``` ## Default Arguments ### Checking Input Existence ```matlab function result = greet(name) if ~exist('name', 'var') name = 'World'; end result = ['Hello, ', name, '!']; end greet() % 'Hello, World!' greet('MATLAB') % 'Hello, MATLAB!' ``` ### Using nargin ```matlab function result = interest(principal, rate, years) if nargin < 3 years = 1; end if nargin < 2 rate = 0.05; end if nargin < 1 principal = 1000; end result = principal * (1 + rate) ^ years; end ``` ## Return Early ### Early Exit ```matlab function result = safeDivide(a, b) %SAFEDIVIDE Divides a by b safely if b == 0 result = NaN; return; end result = a / b; end ``` ## Function Functions ### Passing Functions as Arguments ```matlab % Using @ for function handle f = @(x) x^2 - 2*x + 1; root = fzero(f, 0); % Find root of function % Integration integral(@sin, 0, pi) % 2 ``` ### Optimization ```matlab % Find minimum of function f = @(x) (x-3)^2 + 1; [xMin, fMin] = fminsearch(f, 0); ``` ## Summary - Scripts contain commands; functions accept inputs and return outputs - Function files start with `function` keyword - Anonymous functions: `@(args) expression` - Use `varargin`/`varargout` for variable arguments - Nested functions have access to parent workspace - Use `nargin`/`nargout` to check number of arguments - Use `@` to create function handles

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →