MATLAB Scientific Academy
BEGINNER · 20 min

Write reusable MATLAB programs

Use conditional logic, loops and functions to turn a one-off calculation into a repeatable scientific workflow.

What you will learn

  • Choose between if statements and loops.
  • Write a simple function with inputs and outputs.
  • Use clear names and comments to make code maintainable.

The concept

Use an if/elseif/else block when a program must choose between cases. Use a for loop when the number of iterations is known, and a while loop when a condition controls when to stop.

A function packages a calculation behind a clear interface. Save a function in a file with the same name as the function, and validate inputs where appropriate.

Scientific habit: Before running a program, predict what it will do. Then compare your prediction with the output and explain any difference.

Worked example

This function converts wavelength in nanometres to frequency in terahertz using the speed of light.

example.mMATLAB CODE
function f_THz = wavelengthToFrequency(lambda_nm)
    c = 299792458; % speed of light (m/s)
    lambda_m = lambda_nm .* 1e-9;
    f_THz = (c ./ lambda_m) ./ 1e12;
end

% Example call
f = wavelengthToFrequency(550)

The function uses element-wise operators (.* and ./), so it can also accept a vector of wavelengths.

Try it yourself

Estimate the frequency of green light near 550 nm.

Quick check

Which MATLAB keyword begins a function definition?

Reveal hint and answer
Hint: It appears at the start of the example.
Answer: function.

Where this is used

Functions are useful for repeatable sensor calibration, data cleaning, optical calculations and research code shared across a team.

Academy homeNext: Numerical methods