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.
The Command Window as a Calculator
Section titled “The Command Window as a Calculator”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 =
10Notice 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.
Variables and The Semicolon (;)
Section titled “Variables and The Semicolon (;)”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 * rateThe output of the code above would be:
yearly_interest =
50Adding Comments
Section titled “Adding Comments”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.%}Key Operators: Matrix vs. Element-Wise
Section titled “Key Operators: Matrix vs. Element-Wise”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 Operator | Element-Wise Operator | Purpose |
|---|---|---|
* | .* | 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). |
Special Variables and Constants
Section titled “Special Variables and Constants”MATLAB pre-defines several useful constants and variables:
| Name | Meaning |
|---|---|
ans | Stores the most recent unassigned result. Avoid using in scripts. |
pi | The number π (3.1415…). |
i, j | The imaginary unit, √-1. Can be overwritten, so it’s safer to use 1i for complex numbers. |
Inf | Infinity, e.g., the result of 1/0. |
NaN | Stands for ‘Not a Number’, e.g., the result of 0/0. |
eps | Floating-point relative precision; the distance from 1.0 to the next largest double-precision number. |
Naming Variables
Section titled “Naming Variables”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).
Getting Help
Section titled “Getting Help”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 Windowhelp plot
% Open the full documentation page for a function in a separate windowdoc randSaving and Loading Data
Section titled “Saving and Loading Data”You can save the variables from your workspace into a MATLAB-specific .mat file, and load them back in a later session.
% Create some variablesmyVariable = rand(5);myName = "Alice";
% Save all workspace variables to a file named myData.matsave myData.mat
% Clear the workspace to demonstrate loadingclear
% Load the variables back into the workspaceload myData.matModern 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.