0% found this document useful (0 votes)
5 views

Lecture 5 User Defined Functions

This document covers user-defined functions in MATLAB, detailing upcoming assignments and class instructions. It explains the benefits and syntax of m-file functions, provides examples of creating functions, and introduces anonymous functions. Additionally, it discusses passing functions as arguments and includes various exercises for practical application.

Uploaded by

bobpinnicle10
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 5 User Defined Functions

This document covers user-defined functions in MATLAB, detailing upcoming assignments and class instructions. It explains the benefits and syntax of m-file functions, provides examples of creating functions, and introduces anonymous functions. Additionally, it discusses passing functions as arguments and includes various exercises for practical application.

Uploaded by

bobpinnicle10
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

User-Defined Functions

(Chapter 5—Riggs)

Upcoming assignments:
 Assignment 3 (Matrices and arrays): due today (01/28/25), 11:59 PM
 Assignment 4 (Functions): due January 31, 11:59 PM

For today’s class:


 Create a new sub-folder, named Lecture5, in your ME2543 folder.
 Open MATLAB and change the path to the Lecture5 folder.
 Be sure to save all exercises done in class (we will be using .m files).
User-Defined Functions
(Chapter 5—Riggs)

Inputs Benefits of Using Functions:


 Overall program is reduced in size.
 Structure of program is easier to follow.
Function
 Easier to change or correct a function

Outputs

Functions Used in MATLAB:


 Intrinsic system functions (e.g., sin, exp, log, etc.)
 Built-in functions (e.g., plotting functions, functions for solving equations, etc.)
 User-defined functions:
• m-file functions Complex functions
• Anonymous functions Simple functions
User-Defined m-file Functions

 Use an m-file function (multiple input / multiple outputs and not limited to a single
expression) to break code into easy to develop subdivisions.

 Similar to script files, but all variable are local variables (variables within the function are
erased after execution).

 The building blocks of larger programs.

Basic Syntax:

[ output1, output2, …. ] = function_name( input1, input2, …. )

• Can have multiple inputs and outputs!

• Input and output variables can be scalars, vectors, and arrays.


m-file Functions, Cont’d.

Creating function files—a few rules:

 Can be created using the Script Editor.

 The first executable line of the function file must begin with a function definition line (it can
start with % comments).

 The last executable line should contain an end statement.

 The file must be saved as “function_name.m” (m-file)


m-file Functions, Cont’d.

function [ ouput1, ouput2, …. ] = function_name ( input1, input2, …. )

……. Executable Commands Here

end

Once “end” keyword is hit, function returns output to parent code.

Notes:
• All variable assignments in the function file are local.
• The function file should be in the same working directory as the main code (can explicitly
change directory but need to tell MATLAB).
User-Defined Functions
(Some Examples)

Example 1:

Compute the area of a circle where the radius R is an input value prescribed by the user.

 Create a new script (save the file as area_circ.m):

R = 1.0; % Input the radius in meters

[Area_Circ] = circle(R) Could replace Area_Circ with any other name (local variables)

 Create a new script for the function file (function_circle.m), consisting of:

function [Area_Circ_Value] = function_circle(Radius)


Area_Circ_Value = pi*Radius^2;
Could replace Radius with any other name
end (local variables)
User-Defined Functions
(Some Examples)

Example 1:

Compute the area of a circle where the radius R is an input value prescribed by the user.

 Create a new script (save the file as area_circ.m):

R = 1.0; % Input the radius in meters

[Area_Circ] = circle(R) Could replace Area_Circ with any other name (local variables)

 Create a new script for the function file (circle.m), consisting of:

function [Area_Circ_Value] = circle(Radius)


Area_Circ_Value = pi*Radius^2;
Could replace Radius with any other name
end (local variables)
Variations in the Function Line

function [area_square] = square(side)


File name: square.m 1 input & 1 output

function area_square = square(side)


File name: square.m Brackets can be eliminated for 1 output.

function volume_box = box(height, width, length)


File name: box.m 3 inputs & 1 output

function [area_circle, circum] = circle(radius)


File name: circle.m 1 input & 2 outputs

function plotmyfigure(variable1, variable2)


File name: plotmyfigure.m No outputs & 2 inputs (e.g., only generates a plot)
In-Class Exercises

Example 2. Using the Script Editor, create a function file (function_calc.m)


that computes:

Write the function such that x can be a vector.

 Once created, call the function in a script (create a new m-file, Example_2.m)
to compute the following:

a. f(x) when x = 3
b. f(x) when x = [1, 2, 3, 4]
In-Class Exercises

 Create a new m-file for each problem

Example 3. Create a function “function_max_number” that given three numbers as input returns the
maximum number of the three input variables. The input numbers are: 250, 10 and -15.

Example 4. Create a function “function_operations” that given a vector as input returns: 1) the
minimum value, 2) the sum of all elements in the vector, and 3) the norm of the vector.

Solve this exercise for v1 = [1, 10, -2, 5] and v2 = [17, -8, 4, 7, 18].
Anonymous Functions
(Simple Functions)

An Anonymous Function:
• Multiple input/single output function in a single expression.
• Enable you to create a simple function without having to create, name, and save an m-file
function.

Constructing an Anonymous Function:


• Can be constructed at the MATLAB Command Line or within another function or script file.

Syntax:
func_name = @ (arglist) expr

func_name = the function name


arglist = comma separated list of input arguments
expr = any single, valid MATLAB expression
Anonymous Functions
(Some Examples)

Example 5:
xsquared = @ (x) x^2;
Thus, to execute in MATLAB code, you only need to specify:
xsquared (5)
Note: Anonymous functions can have multiple
ans =
inputs but only one output (scalar, vector, or matrix).
25

Example 6:
Cyl_Volume = @ (Radius, Height) pi*Radius^2*Height;
Thus, in MATLAB code:
Cyl_Volume (0.1, 1)
xsquared and Cyl_Volume are the function
ans =
handles/names.
0.0314
Anonymous Functions
(Some Examples)

Example 7:
vec_squared = @ (x) x.^2;
Thus, in MATLAB code:
x= [0 2 4 6 8 10]
y = vec_squared (x)
y=
0 4 16 36 64 100

Example 8:
FA = @ (x) exp(x.^2)./sqrt(x.^2 + 5);
Thus, in MATLAB code:
FA ([1 0 .5 2])
FA =
1.1097 0.5604 18.1994
More Exercises

 Create a new script (m-file)

Example 9.

a) Using MATLAB built-in functions, create a 10x10 matrix where all elements = 1 and a 10x10
matrix where the diagonal elements = 3 and off-diagonal elements = 0. Do not manually
create the matrices.

b) Create an anonymous function that adds the two matrices.


func_name = @ (input1, input2, …) expression

c) Extract a submatrix from the result that contains rows 5-10 and columns 5-10.
Functions as Arguments to Functions
(Passing Functions to Functions)

 It is sometimes necessary to pass a function to another function:

• subfunction—function that is used by another function.


• primary function—the function that uses the subfunction.

 The function handle/name (subfunction) can be passed as an input argument to the primary
function:

• For m-file functions, add an @ to the subfunction name; e.g.,

primary_function_name (@subfunction_name, …. )
Functions as Arguments, Cont’d.
(An Example)

Example:

1. Create a function f1 that computes the square of a vector (fct_f1.m):


function [f] = fct_f1(x)
f = x.^2 ;
end
2. Create a function fct_plot that will call “fct_f1” to find the square of the vector and plot it
(fct_plot.m).
function fct_plot(fct_random, x)
y = fct_random(x);
plot(x,y); A function of a function!
end
3. Write the main program that initializes x and calls fct_plot (Main.m)
clc; clear all;
x = [ 1 3 5 7 9 11];
fct_plot(@fct_f1, x);

You might also like