Matlab Basics

size(x): Dimensions of matrix x.

length(x): Maximum length across all dimensions of x.

zeros(1,2): Generates a matrix of zeros with 1 row and 2 columns.

ones(2,3): Generates a matrix of ones with 2 rows and 3 columns.

eye(2): Creates a 2x2 identity matrix with 1s on the diagonal and 0s elsewhere.

round(x): Rounds x to the nearest integer.

ceil(x): Rounds x up to the nearest integer.

floor(x): Rounds x down to the nearest integer.

repmat([1,2],2, 3): Replicates the array [1,2] into a 2x3 matrix, such as [1,2,1,2,1,2; 1,2,1,2,1,2].

diff(x): Calculates the forward difference of x, i.e., the difference between consecutive elements.

Logical operators: >, <, ==, ~=, &&, ||.

Function

1
2
3
4
5
6
7
8
9
% Define a function
function volume = calcVolume(r)
% Description
h = 1;
volume = pi*(r^2)*h;
return

% Call the function
wheel = calcVolume(5)

for Loop

1
2
3
for i = 1:size(EEG,1)
filteredEEG(i,:)=filter(EEG(i,:));
end

Space Allocation

1
2
3
4
filteredEEG = zeros(size(EEG));  % Allocate space beforehand to reduce memory usage
for i = 1:size(EEG,1)
filteredEEG(i,:)=filter(EEG(i,:));
end

Data Type: Cell

1
2
3
4
5
6
image{1} = 'bear';
image{2} = [1 3 5];
image{3} = 'tiger';

>> image{3}(1:2)
>> 'ti'

Data Type: structure

1
2
3
4
5
subject(1).label = 'S1';
subject(1).samplingFreq = 200;
subject(1).EEG = [..., ..., ...]
...
subject(2).label = 'S2'

Multidimensional Matrix

1
2
3
4
EEG(:,:,1); % Outputs the first page
% EEG(row, column, page)

squeeze(EEG(:,2,:)) % Outputs and compresses the dimension

📌 How to improve Matlab’s computational speed?

  1. Matrix initialization\
  2. Prefer matrix operations, avoid loops\
  3. Store in row form rather than column form, i.e., [1,2,3,…] instead of [1;2;3;…]\
  4. Use Matlab profiler to identify time-consuming segments.

Disclaimer: This blog content serves as class notes, shared for educational purposes. Some images and content are sourced from textbooks, lecture materials, and the internet. If there are any copyright concerns, please contact aursus.blog@gmail.com for removal.

Translation is done by GPT.