UNIT 1: MATLAB Fundamentals & Core Programming Concepts
1.0 Introduction to MATLAB Environment & Basics
-
MATLAB Desktop Interface: Integrated environment with key panels:
-
Command Window: For executing commands line-by-line.
-
Workspace: Displays current variables in memory.
-
Current Folder: File browser for project directories.
-
Editor: For writing and saving scripts (
.mfiles). -
Figures: Window for displaying plots and graphics.
-
-
Getting Started:
-
Execute commands by pressing Enter in the Command Window.
-
Suppress output with a semicolon (
;) at the end of a statement. -
Getting Help:
-
help <function>: Text-based help in Command Window. -
doc <function>: Detailed documentation in a separate browser window. -
lookfor <keyword>: Searches for functions containing the keyword in their first line of help.
-
-
-
Variables & Assignment:
-
Created by assignment:
variable_name = value; -
Naming Rules: Start with a letter, can contain letters, digits, underscores. Case-sensitive (
A≠a). -
No need for explicit declaration or type definition.
-
-
Basic Arithmetic: Follows standard order of operations (PEMDAS). Operators:
+,-,*,/,^(exponentiation). -
Common Mathematical Functions: Element-wise operations on arrays.
sin,cos,exp,log(natural log),log10,sqrt,abs,round,floor,ceil. -
Formatting Output:
formatcommand changes display precision.-
format short(default): 4 decimal digits. -
format long: 15 digits. -
format bank: 2 decimal digits (currency). -
format rat: Rational approximation.
-
[!TIP] Use
;to keep the Command Window clean during long calculations. Always check the Workspace to confirm variable creation.
2.0 Data Types, Arrays, and Matrices (The Core of MATLAB)
2.1 Fundamental Data Types
| Type | Description | Example |
|---|---|---|
| Numeric | Default is double. Others: single, int8, int16, int32, int64, uint8... |
x = 3.14; (double) |
| Logical | true (1) or false (0). Result of logical operations. |
tf = (5 > 3); |
| Character | 1-D array of characters, enclosed in single quotes ' ' |
c = 'A'; |
| String | String array (modern), enclosed in double quotes " " |
str = "Hello"; |
| datetime, categorical | Specialized types for dates/times and categorical data. | d = datetime('now'); |
2.2 Creating Vectors and Matrices
-
Explicit Listing: Row vectors:
[1, 2, 3]or[1 2 3]. Matrices:[1 2; 3 4](semicolon = new row). -
Colon Operator (
:):start:step:endorstart:end(step=1).- Example:
1:5→[1 2 3 4 5],1:0.5:3→[1.0 1.5 2.0 2.5 3.0].
- Example:
-
Key Functions:
-
zeros(m,n)/zeros(n)→m x nmatrix of zeros. -
ones(m,n)→ Matrix of ones. -
eye(n)→n x nidentity matrix. -
rand(m,n)→ Uniformly distributed random numbers in (0,1). -
randn(m,n)→ Standard normal (Gaussian) random numbers. -
linspace(a,b,n)→nlinearly spaced points betweenaandb. -
logspace(a,b,n)→nlogarithmically spaced points between10^aand10^b.
-
2.3 Matrix and Array Operations
| Operation | Matrix (Linear Algebra) | Array (Element-wise) |
|---|---|---|
| Multiplication | A * B (requires size(A,2)==size(B,1)) |
A .* B (same size) |
| Division | A / B ≈ A * inv(B)<br>A \ B ≈ inv(A) * B |
A ./ B (same size) |
| Exponentiation | A ^ n (matrix power, A must be square) |
A .^ n (each element raised to n) |
| Transpose | A.' (non-conjugate)<br>A' (conjugate transpose for complex) |
Same operators apply |
2.4 Subscripting and Indexing
-
Single Subscript (Linear Indexing): Counts down columns.
A(3)is the 3rd element ofA(column-major order). -
Multiple Subscripts:
A(row, col).A(2,3)is element in 2nd row, 3rd column. -
Colon (
:) Selection:-
A(:, j)→ entirej-th column. -
A(i, :)→ entirei-th row. -
A(:)→ all elements as a single column vector.
-
-
Logical Indexing: Use a logical array (same size as
A) as a mask.A = [1 2 3; 4 5 6]; idx = A > 3; % [0 0 0; 1 1 1] B = A(idx); % B = [4 5 6]
2.5 Manipulating Matrices
-
size(A)→[rows, cols]. -
length(A)→ Largest dimension (for vectors, number of elements). -
numel(A)→ Total number of elements. -
reshape(A, m, n)→ Change dimensions (total elements must match). -
fliplr(A),flipud(A),rot90(A)→ Flip/rotate. -
repmat(A, m, n)→ Replicate matrixm-by-ntimes. -
cat(dim, A, B, ...)→ Concatenate along dimensiondim(1=rows, 2=cols).
2.6 Character Arrays and Strings
-
Character Array:
'text'→1x4char array. Usecharto create. -
String Array:
"text"→1x1string scalar. Usestringto convert. -
Concatenation:
[str1, str2]orstrcat(str1, str2)for strings/chars. -
Comparison:
==for char arrays (element-wise).strcmp/strcmpifor string/char comparison.
[!TIP] Matrix vs. Array Operations is a classic exam trap.
*is matrix multiplication (linear algebra)..*is element-wise. Always match dimensions for.*,./,.^.
3.0 Program Flow Control
3.1 Conditional Statements
-
if/elseif/else:if condition1 % code elseif condition2 % code else % code end- Condition must be scalar logical or convertible to scalar. For array conditions, use
any(condition)orall(condition).
- Condition must be scalar logical or convertible to scalar. For array conditions, use
-
switch/case/otherwise:switch expression case value1 % code case {value2, value3} % multiple cases % code otherwise % code end- More readable for multiple discrete values. Uses
==for comparison.
- More readable for multiple discrete values. Uses
3.2 Looping Constructs
-
forLoop: Iterates over elements of a vector.for i = 1:10 % code end % or for a specific vector: for val = [10, 20, 30] % val takes each value end -
whileLoop: Repeats as long as condition is true.while condition % code end -
Loop Control:
-
break: Exit the innermost loop immediately. -
continue: Skip remaining code in current iteration, move to next.
-
3.3 Vectorization
-
Concept: Replacing
for/whileloops with array operations and built-in functions that operate on entire arrays at once. -
Why? MATLAB is optimized for matrix/array operations. Vectorized code is shorter, clearer, and dramatically faster.
-
Example:
% Non-vectorized (slow) for i = 1:length(x) y(i) = x(i)^2 + 2*x(i); end % Vectorized (fast) y = x.^2 + 2.*x;
[!TIP] Always ask: "Can this be done with a single array operation?" before writing a loop. This is a key best practice for performance.
4.0 Functions and Scripts
4.1 Scripts vs. Functions
| Feature | Script | Function |
|---|---|---|
| Workspace | Runs in base workspace. Variables created are accessible after execution. | Has its own local workspace. Variables inside do not affect base workspace (unless global). |
| Input/Output | No explicit inputs/outputs. Relies on base workspace variables. | Has defined input and output arguments. |
| Reusability | Low. Tied to specific variable names. | High. Can be called with any arguments. |
| File | .m file without function line. |
.m file starting with function line. |
4.2 Creating Functions
-
Syntax (in a file named
myFunc.m):function [out1, out2] = myFunc(in1, in2, in3) % Optional help text % Function body out1 = in1 + in2; out2 = in1 * in3; end -
nargin: Number of actual input arguments passed. -
nargout: Number of actual output arguments requested. -
Local Functions: Multiple functions in a single file (primary function first, others after).
-
Nested Functions: Functions defined inside another function. Share parent function's workspace.
4.3 Scope of Variables
-
Local: Default. Only accessible within the function where defined.
-
Global: Shared across functions and base workspace. Declare with
global varNamein every function and base workspace that uses it. Use sparingly. -
Persistent: Retains value between function calls. Declare with
persistent varNameinside a function. Initialized only on first call.
4.4 Anonymous Functions
-
Single-expression functions defined in one line.
f = @(x) x.^2 + 2*x + 1; % f is a function handle y = f(5); % Evaluates at x=5 -
Can capture workspace variables (at time of creation).
4.5 Function Handles
-
A variable that "points" to a function.
-
@functionName→ Handle to named function. -
@(args) expression→ Handle to anonymous function.
-
-
Used to pass functions as inputs to other functions (e.g.,
fplot,integral).
[!TIP] Functions are the building blocks of modular code. Always write a function for a reusable task. Use
nargin/nargoutfor flexible function interfaces.
5.0 Data Visualization (2D & 3D Plotting)
5.1 Basic 2D Plotting
-
plot(x, y)→ Creates a 2D line plot.xandymust be same size (orxis index if omitted). -
figure→ Opens a new figure window. -
hold on/hold off→ Allows multiple plots on same axes. -
grid on→ Adds grid lines. -
axis([xmin xmax ymin ymax])→ Manually set axis limits. -
title('text'),xlabel('text'),ylabel('text')→ Add labels. -
legend('line1', 'line2')→ Adds a legend.
5.2 Customizing Plots
Specify properties using Name-Value pairs in plot or with set:
plot(x, y, 'LineWidth', 2, 'Color', 'r', 'LineStyle', '--', 'Marker', 'o');
-
Colors:
'r','g','b','c','m','y','k','w'or RGB triplet[0.5 0.2 0.8]. -
Line Styles:
'-','--',':','-.'. -
Markers:
'o','+','*','.','x','s','d','^'.
5.3 Multiple Plots
-
subplot(m,n,p)→ Creates anm x ngrid of axes and makes thep-th one active. -
plotyy(x1,y1, x2,y2)→ Creates two y-axes (left and right) for different data scales.
5.4 Other 2D Plot Types
-
stem(x,y)→ Stem plot (discrete data). -
bar(x,y)→ Vertical bar chart. -
histogram(data)→ Histogram. -
scatter(x,y)→ Scatter plot (markers only). -
loglog,semilogx,semilogy→ Logarithmic scales on one/both axes.
5.5 3D Plotting
-
plot3(x,y,z)→ 3D line/point plot. -
meshgrid(x,y)→ Generates 2D grid matrices for 3D functions. -
mesh(Z)/surf(Z)→ 3D wireframe / surface plot from matrixZ. -
contour(Z)→ 2D contour plot (top-down view of 3D surface). -
surf(x,y,Z)/mesh(x,y,Z)→ Surface/wireframe with specified x,y coordinates.
5.6 Annotating and Saving Figures
-
text(x,y,'string')→ Place text at data coordinates. -
gtext('string')→ Click to place text interactively. -
print('-dpng', 'filename.png')→ Save current figure as PNG. -
saveas(gcf, 'filename.fig')→ Save as MATLAB figure file (.fig). -
exportgraphics(gcf, 'filename.pdf')→ Modern, high-quality export (R2020a+).
[!TIP] Always label your axes (
xlabel,ylabel) and add atitle. For 3D plots, usexlabel,ylabel,zlabel. Usegrid onfor readability.
6.0 Input/Output and File Handling
6.1 User Input
-
input('prompt')→ Displays prompt, waits for user input from Command Window. Returns numeric input by default. -
input('prompt', 's')→ Returns input as a string (character vector).
6.2 Displaying Output
-
disp(A)→ Displays arrayAwithout variable name. Less formatting control. -
fprintf(formatSpec, A1, A2, ...)→ Formatted text output.-
Format Specifiers:
%f(float),%d(integer),%s(string),%e(scientific),%g(general). -
Escape Characters:
\n(new line),\t(tab). -
Example:
fprintf('The value is %.2f\n', x);→ Printsxwith 2 decimals.
-
6.3 Reading/Writing Text Files
-
fid = fopen('filename.txt', 'r')/'w'/'a'→ Open file, get file identifier. Checkfid == -1for error. -
Read:
fscanf(fid, formatSpec, sizeA)ortextscan(fid, formatSpec, N). -
Write:
fprintf(fid, formatSpec, A1, ...). -
fclose(fid)→ Always close file. -
fileread('filename.txt')→ Simple one-line read into a string.
6.4 Reading/Writing Binary/Spreadsheet Files
-
MAT-files:
save('file.mat', 'var1', 'var2')/load('file.mat'). Efficient for saving/loading multiple variables. -
Spreadsheets/CSV:
readmatrix('file.csv')/writematrix(A, 'file.csv'). Modern replacements.xlsread/xlswriteare legacy (Windows/Excel only), avoid for new code.
[!TIP] Always check the return value of
fopen. Afidof-1means the file failed to open (doesn't exist, no permission). Usefclose('all')to close all open files in emergencies.
7.0 Debugging and Code Analysis
7.1 Common Errors
-
Syntax Error: Missing
end,),], misspelled keyword. Caught by MATLAB parser. -
Runtime Error: Occurs during execution (e.g., indexing out of bounds, undefined variable). MATLAB stops and shows error message.
-
Logical Error: Code runs but produces incorrect results. Hardest to find.
7.2 Debugging Tools
-
Editor/Debugger:
-
Set/clear breakpoint (click left margin or
F12). Code pauses before executing that line. -
Step:
F10(Step Over),F11(Step Into). Execute line-by-line. -
Run Section:
Ctrl+Enterruns code between%%section dividers.
-
-
Command Window Debugging Commands:
-
dbstop in file at line→ Set breakpoint. -
dbstop if error→ Stop on any error. -
dbcont→ Continue execution after pause. -
dbquit→ Exit debug mode. -
dbstack→ Show call stack.
-
-
Checking Code:
-
dbtype file→ Display file with line numbers. -
which functionName→ Show path to function being called. -
exist('varName')→ Check if variable/function exists (returns 1 for variable, 2 for file, 5 for built-in).
-
7.3 Profiling Code
-
profile on→ Start performance profiling. -
Run your code.
-
profile viewer→ Open GUI showing time spent in each function. Identifies bottlenecks. -
profile off/profile reset→ Stop/clear profiling.
[!TIP] Use
dbstop if errorearly in debugging. It automatically stops at the line causing the error, letting you inspect variables. The Profiler is essential for optimizing slow code.
8.0 Best Practices and Efficient MATLAB Usage
8.1 Preallocation
-
Problem: Growing an array inside a loop (
A = [A new_element]) forces MATLAB to repeatedly allocate new memory and copy data → very slow. -
Solution: Preallocate the final size before the loop.
A = zeros(1, N); % Preallocate N-element row vector for i = 1:N A(i) = someCalculation(i); end -
Use
zeros,NaN,false,cell,stringsdepending on data type.
8.2 Vectorization
-
Golden Rule: "Think in arrays." Replace loops with array operations and built-in functions (
sum,mean,max,arrayfun, etc.). -
Example: Sum of squares of vector
x→sum(x.^2), not aforloop.
8.3 Code Readability
-
Meaningful Names:
totalRevenue>tr. -
Comments (
%): Explain why, not what (the code should show what). -
Sections (
%%): Create collapsible sections in the Editor. Run sections independently. -
Consistent Formatting: Use MATLAB's automatic formatting (
Ctrl+I).
8.4 Managing Workspace and Path
-
clear varName→ Remove variable from workspace. -
clearvars/clear all→ Remove all variables (clear allalso clears functions from memory). -
clc→ Clear Command Window. -
addpath('folder')→ Add folder to search path (for functions). -
rmpath('folder')→ Remove folder from path. -
savepath→ Save current path for future sessions.
8.5 Avoiding Common Pitfalls
| Pitfall | Solution |
|---|---|
Floating-point comparison (a == b) |
Use tolerance: abs(a-b) < eps or abs(a-b) < 1e-10. |
| Array dimension mismatch | Use size(A), length(A), numel(A) to check. Use .' for non-conjugate transpose if needed. |
| Operator precedence | Use parentheses () to make order explicit. .* has higher precedence than *. |
Forgetting . for element-wise ops |
Remember: .*, ./, .^. Matrix ops (*, /, ^) have strict dimension rules. |
Using == for string comparison |
Use strcmp(str1, str2) or str1 == str2 only for char arrays of same length. |
[!TIP] Preallocation and Vectorization are the two most important techniques for writing efficient MATLAB code. They can turn a script that runs for minutes into one that runs in seconds.