Skip to content

MATLAB - Syntax

MATLAB - Fundamental Syntax and Best Practices

Section titled “MATLAB - Fundamental Syntax and Best Practices”

The MATLAB environment is a powerful interactive platform. You can enter commands directly into the Command Window at the >> prompt, and MATLAB, being an interpreted language, executes them immediately. This makes it ideal for rapid prototyping, data analysis, and learning.

At its simplest, you can perform calculations directly:

5 + 5
ans =
10
3^2 + sin(pi/2) % 3 squared plus the sine of 90 degrees
ans =
10

Notice that if you don’t assign the result to a variable, MATLAB stores it in a temporary variable named ans. It’s fine for quick checks, but in scripts, you should always assign results to descriptive variables.

You create variables using the assignment operator =. If you end a line with a semicolon ;, MATLAB executes the command but suppresses the output from appearing in the Command Window. This is essential for keeping your scripts clean and readable.

% Assign a value to 'principal', output is suppressed.
principal = 1000;
% Assign a value to 'rate', output is suppressed.
rate = 0.05;
% Calculate interest, output is displayed because there is no semicolon.
yearly_interest = principal * rate

The output of the code above would be:

yearly_interest =
50

Good comments are crucial for understandable and maintainable code. Use the percent symbol (%) for single-line comments. For multi-line comments, you can use the block comment operators %{ and %}.

% This is a single-line comment.
x = 9; % This is an in-line comment explaining the purpose of the line.
%{
This is a block comment.
It can span multiple lines and is useful for
temporarily disabling large sections of code.
%}

This is one of the most important concepts in MATLAB. Understanding the difference between matrix operators and element-wise (or array) operators is critical.

Matrix OperatorElement-Wise OperatorPurpose
*.*Multiplication. A*B is matrix multiplication. A.*B multiplies each element of A with the corresponding element of B.
/./Right Division. A/B is roughly A*inv(B). A./B divides each element of A by the corresponding element of B.
\.\Left Division. A\B solves A*x=B. A.\B divides each element of B by the corresponding element of A.
^.^Power. A^2 is matrix power (A*A). A.^2 squares each element of A individually.
'.'Transpose. A' is the complex conjugate transpose. A.' is the non-conjugate transpose (use this if you’re not working with complex numbers).

MATLAB pre-defines several useful constants and variables:

NameMeaning
ansStores the most recent unassigned result. Avoid using in scripts.
piThe number π (3.1415…).
i, jThe imaginary unit, √-1. Can be overwritten, so it’s safer to use 1i for complex numbers.
InfInfinity, e.g., the result of 1/0.
NaNStands for ‘Not a Number’, e.g., the result of 0/0.
epsFloating-point relative precision; the distance from 1.0 to the next largest double-precision number.

Variable names must start with a letter, followed by letters, digits, or underscores. MATLAB is case-sensitive (myVar is different from myvar).

Best Practice: Use descriptive names that indicate the variable’s purpose. Common conventions include camelCase (e.g., interestRate) or snake_case (e.g., interest_rate). Avoid using names of built-in functions (like sum or mean).

Learning to find help on your own is a superpower. MATLAB has excellent built-in documentation.

% Get a quick summary of a function in the Command Window
help plot
% Open the full documentation page for a function in a separate window
doc rand

You can save the variables from your workspace into a MATLAB-specific .mat file, and load them back in a later session.

% Create some variables
myVariable = rand(5);
myName = "Alice";
% Save all workspace variables to a file named myData.mat
save myData.mat
% Clear the workspace to demonstrate loading
clear
% Load the variables back into the workspace
load myData.mat

Modern Practice: For sharing data with other programs, consider using standardized formats like CSV or Excel. Use writematrix, writetable, or writecell to export data, and readmatrix, readtable, etc., to import it.