MATLAB Functions
1. Basics of MATLAB
Setting Up the Environment
To ensure a clean run, start your script with:
clc; % Clears command window
clear; % Clears variables
close all; % Closes all figure windows
format short; % Displays numbers with 5 significant digits
Arrays: Vectors & Matrices
Vectors: One-dimensional arrays (row or column).
A = [1 6 5 9 7]; % Row vector
B = [1,6,5,9,7]; % Alternative syntax
Colon Operator:
C = 1:10; % Generates [1 2 3 ... 10]
D = 1:0.5:10; % Increments by 0.5
Linspace:
E = linspace(0, pi/2, 10); % 10 equally spaced values
Transposing a Vector:
F = A'; % Converts row vector to column vector
Matrices:
Defining a Matrix:
G = [3 5 7; 2 4 6; 9 11 13]; % 3x3 matrix
Combining Matrices:
H = [8 10 12; 14 16 18];
I = [G; H]; % Stacks G and H vertically
Arithmetic Operations
Element-wise operations (use .* , ./ , .^ for element-by-element calculations).
J = A.^2; % Squares each element of A
Loops & Control Statements
For Loop:
for i = 1:2:20
fprintf('Value of i: %d\n', i);
end
While Loop:
a = 10;
while a < 20
fprintf('Value of a: %d\n', a);
a = a + 3;
end
If-Else Statements:
x = 5;
if x < 0
disp('Negative');
else
disp('Non-negative');
end
2. Importing Data
Importing Data Using importdata
Works for .csv, .xlsx, .txt, images, and audio files.
ImportedData = importdata('MATLAB_Import_Example_CSV.csv');
View imported data in the Workspace.
Using csvread (For Numeric Data Only)
Basic usage:
M = csvread('MATLAB_Import_Example_CSV.csv',2,0); % Skip first 2 rows
Cannot handle non-numeric headers.
Using dlmread (Custom Delimiters)
Reads numeric text but requires specifying delimiter.
DLMRead_Imported_Data =
dlmread('MATLAB_Import_Example_Tab_Delimited_Text.txt',2,0);
3. Extracting Data
To reference a specific value (e.g., row 5, column 6 from an imported file called
DLM):
Data_Row5_Col6 = DLM(5,6);
To extract an entire column or row:
Column4 = DLM(:,4); % Extracts all values from column 4
Row4 = DLM(4,:); % Extracts all values from row 4