My simple library

..of useful code



Chapters

Matlab guide

Comprehensive reference for signal generation, analysis, and visualization in MATLAB

Signal Generation

Basic Signals

% Time vector
Fs = 1000;            % Sampling frequency (Hz)
T = 1/Fs;             % Sampling period
t = 0:T:1-T;          % Time vector (1 second)

% Sine wave
f = 5;                % Frequency (Hz)
sine_wave = sin(2*pi*f*t);

% Cosine wave
cos_wave = cos(2*pi*f*t);

% Square wave
square_wave = square(2*pi*f*t);

% Sawtooth wave
sawtooth_wave = sawtooth(2*pi*f*t);

% Pulse train
pulse_train = pulstran(t, 0:1/f:1, 'rectpuls', 0.05);

Random Signals

% White noise
white_noise = randn(size(t));

% Pink noise (1/f noise)
pink_noise = dsp.ColoredNoise('Color', 'pink', 'SamplesPerFrame', length(t));
pink_noise = pink_noise();

% Impulse signal
impulse = zeros(size(t));
impulse(1) = 1;

Matrix Operations

Matrix Creation

% Basic matrices
A = [1 2 3; 4 5 6; 7 8 9];  % 3x3 matrix
B = zeros(3, 2);            % 3x2 zeros matrix
C = ones(2, 4);             % 2x4 ones matrix
D = eye(3);                 % 3x3 identity matrix

% Special matrices
E = magic(3);               % Magic square
F = rand(3, 3);             % Uniform random
G = randn(3, 3);            % Normal random

% From vectors
v = 1:5;                    % Row vector [1 2 3 4 5]
M = v' * v;                 % Outer product

Matrix Operations

% Basic operations
sum_A = sum(A);             % Column sums
mean_A = mean(A);           % Column means
max_A = max(A);             % Column maximums

% Matrix algebra
A_transpose = A';           % Transpose
A_inverse = inv(A);         % Inverse (if square and non-singular)
A_det = det(A);             % Determinant
[V, D] = eig(A);            % Eigenvalues and eigenvectors

% Element-wise operations
A_squared = A.^2;           % Element-wise square
A_times_B = A .* B;         % Element-wise multiplication (if same size)

Fourier Analysis

FFT (Fast Fourier Transform)

% Generate signal
Fs = 1000;            % Sampling frequency
t = 0:1/Fs:1-1/Fs;    % Time vector
x = sin(2*pi*50*t) + 0.7*sin(2*pi*120*t);

% Compute FFT
N = length(x);        % Number of samples
X = fft(x);           % Compute FFT
X_mag = abs(X);       % Magnitude spectrum
f = (0:N-1)*(Fs/N);   % Frequency vector

% Plot single-sided spectrum
X_mag_ss = X_mag(1:N/2+1);
f_ss = f(1:N/2+1);
plot(f_ss, X_mag_ss);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Single-Sided Spectrum');
FFT Explanation

The FFT converts a time-domain signal into its frequency components. Key points:

  • The output is complex-valued, showing magnitude and phase at each frequency
  • The first half of the FFT output (up to Nyquist frequency) contains all the information
  • Magnitude shows signal strength at each frequency
  • Phase shows timing relationships between components

FFTShift

% Shift zero-frequency component to center
X_shifted = fftshift(X);
f_shifted = (-N/2:N/2-1)*(Fs/N);

% Plot centered spectrum
plot(f_shifted, abs(X_shifted));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Centered Spectrum (using fftshift)');
FFTShift Explanation

fftshift rearranges the FFT output to put the zero-frequency component at the center. This is useful for:

  • Visualizing spectra with negative and positive frequencies
  • Working with filters in the frequency domain
  • Analyzing signals where DC component is important

Z-Transform and Filtering

Z-Transform Basics

% Define a simple discrete-time system
b = [1, 0.5];        % Numerator coefficients (feedforward)
a = [1, -0.9];       % Denominator coefficients (feedback)

% Compute frequency response
[H, w] = freqz(b, a, 1024, Fs);

% Plot magnitude response
subplot(2,1,1);
plot(w, 20*log10(abs(H)));
title('Magnitude Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Plot phase response
subplot(2,1,2);
plot(w, angle(H));
title('Phase Response');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
Z-Transform Explanation

The Z-transform converts a discrete-time signal into a complex frequency domain representation. In MATLAB:

  • freqz computes the frequency response of a system given its numerator and denominator coefficients
  • The numerator (b) represents the feedforward coefficients
  • The denominator (a) represents the feedback coefficients
  • Poles and zeros can be found with roots function

Filter Design and Application

% Design a lowpass Butterworth filter
fc = 100;            % Cutoff frequency (Hz)
order = 4;           % Filter order
[b, a] = butter(order, fc/(Fs/2));

% Apply filter to noisy signal
noisy_signal = sin(2*pi*50*t) + 0.5*randn(size(t));
filtered_signal = filter(b, a, noisy_signal);

% Plot results
figure;
subplot(2,1,1);
plot(t, noisy_signal);
title('Original Noisy Signal');
subplot(2,1,2);
plot(t, filtered_signal);
title('Filtered Signal');

Plotting Guide

Basic Plotting

% Line plot
x = 0:0.1:10;
y = sin(x);
plot(x, y, 'b-', 'LineWidth', 2);
title('Sine Wave');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

% Multiple plots
y2 = cos(x);
hold on;
plot(x, y2, 'r--', 'LineWidth', 2);
legend('Sine', 'Cosine');
hold off;

% Subplots
figure;
subplot(2,1,1);
plot(x, y);
title('Sine Wave');
subplot(2,1,2);
plot(x, y2);
title('Cosine Wave');

Advanced Plotting

% Stem plot (for discrete signals)
n = 0:20;
x = 0.9.^n;
stem(n, x, 'filled');
title('Discrete Signal');

% Spectrogram
Fs = 1000;
t = 0:1/Fs:2;
x = chirp(t, 0, 1, 250);  % Frequency sweep
spectrogram(x, 256, 250, 256, Fs, 'yaxis');
title('Spectrogram of Chirp Signal');

% 3D Surface plot
[X, Y] = meshgrid(-2:0.1:2);
Z = X.*exp(-X.^2 - Y.^2);
surf(X, Y, Z);
title('3D Surface Plot');
xlabel('X');
ylabel('Y');
zlabel('Z');
colorbar;

Signal Processing Toolbox

Common Signal Processing Functions

Function Description
conv Convolution of two signals
xcorr Cross-correlation
filter Digital filter implementation
resample Change sampling rate
hilbert Analytic signal (Hilbert transform)
fir1, butter Filter design functions
spectrogram Time-frequency analysis
pwelch Power spectral density estimate

Practical Example: Signal Denoising

% Create noisy signal
Fs = 1000;
t = 0:1/Fs:1;
f = 10;
clean_signal = sin(2*pi*f*t);
noise = 0.5*randn(size(t));
noisy_signal = clean_signal + noise;

% Moving average filter
window_size = 10;
b = ones(1, window_size)/window_size;
filtered_signal = filter(b, 1, noisy_signal);

% Plot results
figure;
subplot(3,1,1);
plot(t, clean_signal);
title('Clean Signal');
subplot(3,1,2);
plot(t, noisy_signal);
title('Noisy Signal');
subplot(3,1,3);
plot(t, filtered_signal);
title('Filtered Signal');
Signal Processing Workflow
  1. Generate or acquire the signal
  2. Pre-process (filter, normalize, remove artifacts)
  3. Analyze (time-domain, frequency-domain, time-frequency)
  4. Visualize results
  5. Extract features or make decisions

Useful MATLAB Tips

Performance Tips

% Preallocate arrays for speed
N = 10000;
result = zeros(1, N);  % Preallocate
for k = 1:N
    result(k) = someCalculation(k);
end

% Vectorize operations when possible
x = 1:10000;
y = sin(x);            % Vectorized is faster than loop

% Use parfor for parallel computing
parfor i = 1:100
    results(i) = longCalculation(i);
end

% Profile your code
profile on;
myFunction();
profile viewer;

Common Pitfalls

% 1. Indexing starts at 1 (not 0)
A = [10 20 30];
A(1)   % Returns 10 (not A[0] like in some languages)

% 2. Matrix vs. element-wise operations
A = [1 2; 3 4];
B = [5 6; 7 8];
A * B   % Matrix multiplication
A .* B  % Element-wise multiplication

% 3. Transpose of complex matrices
A = [1+2i, 3+4i];
A'      % Hermitian (conjugate) transpose
A.'     % Regular transpose
Debugging Tips
  • Use disp or fprintf for variable inspection
  • Set breakpoints with dbstop or in the editor
  • Check dimensions with size and whos
  • Use try-catch blocks for error handling