MATLAB
Functions and Scripts
Define functions in separate files or at end of scripts.
By EZ4Code Team
functionanonymous
Code
% In a file named myfunc.m:
function [output1, output2] = myfunc(input1, input2)
% MYFUNC Description
output1 = input1 + input2;
output2 = input1 * input2;
end
% Anonymous functions (inline)
square = @(x) x.^2;
square(5) % 25
square([1 2 3]) % [1 4 9]
% Function handles
f = @sin;
f(pi/2) % 1
% Multiple outputs
[a, b] = myfunc(3, 4);Explanation
MATLAB functions must be in files matching the function name, or at the end of a script (R2016b+). Anonymous functions (@) are closures for short expressions. Function handles (@func) let you pass functions as arguments, enabling functional-style programming.
More MATLAB Snippets
Matrix Creation and Operations
Create and operate on matrices in MATLAB.
2D Plotting
Create line plots with labels, legends, and styling.
Cell Arrays and Structs
Heterogeneous data containers in MATLAB.
File I/O
Read and write .mat, .csv, and text files.
ODE Solvers
Solve ordinary differential equations with ode45.
Signal Processing (FFT)
Compute and visualize the FFT of a signal.