1.0 Control Flow & Logical Operations
1.1 Conditional Statements
-
if/elseif/else: Executes code blocks based on logical conditions.if condition1 % code elseif condition2 % code else % code end[!TIP] Conditions must evaluate to scalar logical (
true/false). Use&&(AND) and||(OR) for combining scalar conditions inifstatements to avoid array operation errors. -
switch/case: Efficient for multiple discrete values (numbers or strings).switch expression case value1 % code case {value2, value3} % Multiple cases % code otherwise % default code end
1.2 Looping Constructs
-
forloops: Iterates over elements of a vector (often created with:).for i = 1:10 % or for i = [1, 3, 5] % code using i end[!TIP] Avoid modifying the loop index
iinside the loop. -
whileloops: Repeats while condition remainstrue. Must ensure termination condition exists to prevent infinite loops.while condition % code that eventually makes condition false end -
Nested Loops: Common for matrix traversal (rows, then columns). Performance degrades with deep nesting; seek vectorization.
1.3 Logical & Relational Operators
| Operator | Description | Example |
|---|---|---|
==, ~=, >, <, >=, <= |
Relational (element-wise) | A > 0 |
& |
Element-wise AND | [1 0] & [0 1] → [0 0] |
| ` | ` | Element-wise OR |
~ |
Element-wise NOT | ~[1 0] → [0 1] |
&& |
Short-circuit AND (scalar only) | Stops if first condition is false |
| ` | ` |
Key Application: Logical Indexing
A(A > 5) = 0; % Set all elements >5 to 0
B = A(A >= 0 & A <= 10); % Extract elements in [0,10]
[!TIP]
&&and||are forif/whileconditions with scalars. Use&and|for element-wise array operations and logical indexing.
2.0 Functions & Code Modularity
2.1 Creating and Using Functions
-
Syntax (in a file named
myFunc.m):function [out1, out2] = myFunc(in1, in2) % HELP TEXT (shows with 'help myFunc') % Function description out1 = in1 + in2; out2 = in1 * in2; end -
Calling:
[a,b] = myFunc(2,3); -
File Naming: The primary function's name must match the
.mfilename.
2.2 Function Types & Scope
| Type | Definition | Key Features |
|---|---|---|
| Primary | First function in a file | Name = filename; callable from outside |
| Subfunction | Defined after primary in same file | Local to file; not visible outside |
| Anonymous | f = @(x) x.^2 + 1; |
Single expression; no file; captures workspace |
| Nested | Function defined inside another | Can access parent's variables; parent must be called |
-
Variable Scope:
-
base: Command window workspace. -
caller: Workspace of function that called the current function. -
function: Local workspace of the current function (default). -
global: Shared across workspaces (use sparingly). -
persistent: Retains value between function calls (like static).
-
[!TIP] Scripts share the base workspace. Functions have their own workspace, preventing variable clashes—prefer functions for modular, reusable code.
2.3 Function Handles & feval
-
Handle:
fh = @sin;Creates a reference to the function. -
Passing:
result = mySolver(fh, x0);wheremySolverusesfh(x). -
feval: Executes a function from a handle or string:y = feval(fh, x);(Use handle directlyfh(x)is preferred).
3.0 Data Import, Export, & File I/O
3.1 Basic File Operations
fid = fopen('data.txt', 'r'); % 'r'=read, 'w'=write, 'a'=append
if fid == -1, error('File not found'); end
data = fscanf(fid, '%f %f', [2 Inf]); % Read formatted numbers
fclose(fid);
[!TIP] Always check
fid ~= -1afterfopen. Usefprintf(fid, '%6.2f\n', x)for formatted writing.
3.2 High-Level Import/Export Functions
| Function | Use Case | Data Type |
|---|---|---|
load / save |
MATLAB .mat files (binary/ASCII) |
Variables, matrices |
readmatrix / writematrix |
Modern numeric matrix I/O (replaces csvread/write) |
Numeric matrix |
readtable / writetable |
Heterogeneous column data (headers, mixed types) | table object |
importdata |
Flexible import (auto-detects delimiters, headers) | Struct (data, textdata) |
[!TIP] For CSV/Excel with headers →
readtable. For pure numeric grids →readmatrix.
3.3 Text Files & Strings
-
textscan: Powerful for complex, formatted text files.fid = fopen('log.txt'); C = textscan(fid, '%s %f %d', 'Delimiter', ',', 'HeaderLines', 2); fclose(fid); -
String Ops:
strcat,split,strfind,strcmp/strcmpi(case-sensitive/insensitive). -
Conversion:
string(new) vs.char(cell array of char vectors). Usestring()for modern code.
4.0 Debugging, Profiling, & Code Efficiency
4.1 Debugging Tools
-
Editor/Debugger: Set breakpoints (click margin), step (F10=next, F11=step into), run to cursor.
-
Command-line:
dbstop if error % Stops at error dbstop in myFunc at 15 % Stops at line 15 in myFunc dbstack % Shows call stack -
Workspace Inspection:
who,whos,disp,fprintffor formatted output.
4.2 Performance & Profiling
-
Preallocation: MOST CRITICAL OPTIMIZATION. Allocate array size before loop.
A = zeros(1000, 1000); % GOOD for i = 1:1000 A(i) = i^2; % Fast assignment endA = []; % BAD for i = 1:1000 A(i) = i^2; % Slow: resizes array each iteration end -
Vectorization: Replace loops with matrix/array operations.
% Loop (slow) for i = 1:n B(i) = A(i) * 2; end % Vectorized (fast) B = A .* 2; -
Profiler:
profile on mySlowFunction() profile viewer % Shows time per function/line profile off
[!TIP] Always preallocate! Use
tic/tocfor quick timing. Profiler identifies exact bottlenecks.
5.0 Advanced Data Structures & Practical Applications
5.1 Cell Arrays
-
Creation:
C = {1, 'text', [1 2 3]};orcell(2,3). -
Access:
-
C(1)→ returns a cell containing1. -
C{1}→ returns the contents (1).
-
-
Use: Store heterogeneous data (different types/sizes in one array).
-
Common:
cellfun(@func, C)appliesfuncto each cell's contents.
5.2 Structures
-
Creation:
s.name = 'Alice'; s.scores = [95 88 92]; -
Access:
-
s.name→'Alice'. -
s.(fieldName)→ dynamic field access.
-
-
Use: Organize related dissimilar data (metadata, experiment parameters).
-
Nested:
s.experiment.date = '2023-10-01'; -
Conversion:
T = struct2table(s)for tabular analysis.
5.3 Practical Data Pipeline (Synthesis)
-
Import:
data = readtable('raw_data.csv'); -
Clean:
data = data(data.Value > 0, :);(logical indexing) -
Transform: Use a function for complex calculations.
-
Analyze: Vectorized operations on table variables:
mean(data.Score). -
Export:
writetable(data, 'clean_data.csv');
6.0 Best Practices & Common Pitfalls
6.1 Script vs. Function
| Feature | Script | Function |
|---|---|---|
| Workspace | Shares base |
Own local workspace |
| Input/Output | Uses variables directly | Explicit input/output args |
| Reusability | Low | High |
| Use When | Quick exploration, plotting | Any reusable, modular task |
6.2 Input Validation (Inside Functions)
function out = myFunc(a, b)
narginchk(2, 2); % Require exactly 2 inputs
validateattributes(a, {'numeric'}, {'scalar', 'positive'});
% ... function body ...
end
6.3 Top 10 Common Mistakes
-
Forgetting
.for element-wise ops (.*,./,.^). -
Using
=(assignment) instead of==(equality) in conditions. -
Poor/no preallocation causing slow loops.
-
Misunderstanding
&vs&&,|vs||. -
Incorrect cell vs. content indexing (
()vs{}). -
Ignoring function scope (expecting function to modify base workspace).
-
Using
csvread/csvwrite(deprecated) instead ofreadmatrix/writematrix. -
Not checking
fidafterfopen. -
Using
lengthon matrices (usesize(A, dim)). -
Writing unvectorized code when a matrix operation exists.
[!TIP] Always preallocate. Use
&/|for arrays,&&/||for scalars in conditions. Prefer functions over scripts for modularity.