MATLAB allows users to define their own functions, in addition to built-in functions. This improves code organization, reduces repetition, and improves readability. User-defined functions can be stored in separate files and called from scripts or other functions. They are essential for building scalable and maintainable engineering code.

The MATLAB Help Center includes a guide to Create Functions in Files.

Purpose of Functions

Functions are reusable blocks of code that accept inputs, perform operations, and return outputs. They are especially useful when a calculation needs to be performed multiple times with different inputs. They can also abstract the details of a complex operation into a simpler interface. For example, when you call sin(x) you are not particularly interested in the algorithm used to compute the sine of an angle; you just want the answer.

Syntax

User-defined functions in MATLAB follow this general syntax:

function [out1, out2, ...] = function_name(in1, inp2, ...)
    % Code to compute outputs
end

The function must be saved in a file with the same name as the function. In this example, it would be saved in function_name.m. The body of the function contains the calculations. Comments can be added using % to describe the purpose of each step.

Example: Stress on a Beam

Question

A force of 5000 N is applied to a beam with a cross-sectional area of 0.002 m2. Given the formula for axial stress:

\[\sigma = \frac{F}{A}\]

write a MATLAB function that calculates stress for any $F$ and $A$, then use it to find the stress for the givens above. Express your answer in MPa.

Solution

Here the stress equation is implemented in a function. It takes two inputs, force and area, and computes the pressure. Here’s the function:

function pres = pressure(force, area)
    pres = force ./ area;
end

Using this function in a script:

% Givens
F = 5000;  % N
A = 0.002; % m^2

% Calculate pressure
p = pressure(F, A);

% Display output
p_MPa = p*1e-6;
disp(['Pressure:' num2str(p_MPa)])

Pressure:2.5

Notice the variable names are slightly different. Within the function, the first input is assigned to the variable force and the second input is assigned to the variable area. In the script that calls pressure, the variable F is the first input and A is the second. The value of F in the script is assigned to force within the function, and the same for area.

Also notice that ./ is used instead of /. The question asked to find the value of $\sigma$ for a scalar $F$ and scalar $A$, however in the future we may have arrays for force and area. Using the ./ is not necessary for scalars, but it makes the function capable of handling arrays in the future.

Input and Output Behavior

Functions can accept a variety of data types as inputs. This includes scalars, vectors, matrices, and structures. MATLAB does not require you to specify what type each input should be. All inputs are contained within a set of parentheses that follow the function name. The outputs are contained within square brackets and come before the function name and assignment operator.

function [area, perimeter] = rectangle_props(width, height)
    area = width .* height;
    perimeter = 2 * (width + height);
end

This function takes two inputs, width and height, and returns two outputs, area and perimeter. To capture both outputs when calling the function, list them in square brackets on the left side of the assignment: [a, p] = rectangle_props(3, 4). If you only need one output, you can omit the brackets and capture just the first one: a = rectangle_props(3, 4).

Scope and Variables

Variables defined inside a function are local to that function. They do on affect variables in the calling script unless returned explicitly. This helps prevent accidental overwriting of data and improves modularity.

Best Practices

  • Use descriptive names for functions and their inputs/outputs, so a reader can guess what they do without reading the body
  • Include comments describing the purpose of the function and any non-obvious steps
  • Avoid hardcoding values inside a function - pass them in as inputs instead, so the function stays reusable
  • Keep the scope of each function narrow - one task per function

Reading Questions

  1. What are the benefits to user-defined functions in MATLAB?
  2. What must the filename be for a file containing a user-defined function?
  3. Describe which variables from a script are and are not available to a function called by that script.
  4. How would you define a function that calculates the volume of a cylinder given its radius and height?
  5. How can functions improve the readability and maintainability of your code?

Practice Problem: Rotor Disk Loading

Disk loading is a helicopter’s weight divided by its rotor disk area, and it’s a quick way to compare how hard different rotorcraft are working their rotors.

\[DL = \frac{W}{\pi R^2}\]

In this practice problem, you’ll write a MATLAB function that calculates disk loading, then use it to compare two helicopters.

Your Task

Write a function named disk_loading.m that takes weight and radius as inputs and returns DL, the disk loading, using the formula above.

Then write a script named rotor_compare.m that starts from the following givens for two helicopters:

weight_a = 6000; % lbf
radius_a = 18; % ft

weight_b = 22000; % lbf
radius_b = 24; % ft

Using your disk_loading function, compute:

  1. DL_a - the disk loading of helicopter A
  2. DL_b - the disk loading of helicopter B
  3. DL_ratio - DL_b divided by DL_a

Your variable names for the three answers above must match exactly (DL_a, DL_b, DL_ratio) so that the checker below can find them.

Checking Your Work

Download check_rotor_compare.m and save it in the same folder as your disk_loading.m and rotor_compare.m files. Make sure that folder is your Current Folder in MATLAB, then run:

>> check_rotor_compare

The checker runs your script and reports whether each of the three values is correct. This is practice, not a graded assignment. If something doesn’t pass, use the feedback to find and fix the issue, then run the checker again.