Skip to main content

OFDM in MATLAB


 

MATLAB Script

% The code is written by SalimWireless.Com

1. Initialization

clc;
clear all;
close all;


2. Generate Random Bits

% Generate random bits
numBits = 100;
bits = randi([0, 1], 1, numBits);


3. Define Parameters

% Define parameters
numSubcarriers = 4; % Number of subcarriers
numPilotSymbols = 3; % Number of pilot symbols
cpLength = ceil(numBits / 4); % Length of cyclic prefix (one-fourth of the data length)


4. Add Cyclic Prefix

% Add cyclic prefix
dataWithCP = [bits(end - cpLength + 1:end), bits];


5. Insert Pilot Symbols

% Insert pilot symbols
pilotSymbols = ones(1, numPilotSymbols); % Example pilot symbols (could be any pattern)
dataWithPilots = [pilotSymbols, dataWithCP];

 

6. Perform OFDM Modulation (IFFT)

% Perform OFDM modulation (IFFT)
dataMatrix = reshape(dataWithPilots, numSubcarriers, []);
ofdmSignal = ifft(dataMatrix, numSubcarriers);
ofdmSignal = reshape(ofdmSignal, 1, []);


7. Display the Generated Data

% Display the generated data
disp("Original Bits:");
disp(bits);
disp("Data with Cyclic Prefix and Pilots:");
disp(dataWithPilots);
disp("OFDM Signal:");
disp(ofdmSignal);

%%%%%%%%%%%%%%%%%%%%%%%%%%% Demodulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


8. Demodulation

% Perform FFT on the received signal
%ofdmSignal = awgn(ofdmSignal, 1000);
ofdmSignal = reshape(ofdmSignal, numSubcarriers, []);
rxSignal = fft(ofdmSignal, numSubcarriers);
%rxSignal = [rxSignal(1,:) rxSignal(2,:) rxSignal(3,:) rxSignal(4,:)];


9. Remove Cyclic Prefix

% Remove cyclic prefix
rxSignalNoCP = rxSignal(cpLength + 1:end);


10. Extract Data Symbols and Discard Pilot Symbols

% Extract data symbols and discard pilot symbols
dataSymbols = rxSignalNoCP(numPilotSymbols + 1:end);


11. Demodulate the Symbols Using Thresholding

% Demodulate the symbols using thresholding
threshold = 0;
demodulatedBits = (real(dataSymbols) > threshold);


12. Plot the Original and Received Bits

figure(1)
stem(bits);
legend("Original Information Bits")

figure(2)
stem(demodulatedBits);
legend("Received Bits")

Output

 

 
Fig 1: Original Information Bits
 
 
 
 
 
Fig 2: OFDM Signal
 
 
 
 
Fig 3: Received Demodulated Bits

 

Copy the MATLAB Code above from here

 

 

MATLAB Code for OFDM using QPSK

% The code is written by SalimWireless.Com
clc;
clear all;
close all;

% Generate random bits (must be even for QPSK)
numBits = 20;
if mod(numBits, 2) ~= 0
numBits = numBits + 1; % Make even
end
bits = randi([0, 1], 1, numBits);

% QPSK Modulation (2 bits per symbol)
bitPairs = reshape(bits, 2, []).';
qpskSymbols = (1/sqrt(2)) * ((2*bitPairs(:,1)-1) + 1j*(2*bitPairs(:,2)-1)); % Gray-coded

% Parameters
numSubcarriers = 4; % Number of OFDM subcarriers
numPilotSymbols = 3; % Number of pilot symbols
cpLength = ceil(length(qpskSymbols) / 4); % Cyclic prefix length

% Insert pilot symbols
pilotSymbols = ones(1, numPilotSymbols); % Example pilot symbols (BPSK pilots)
dataWithPilots = [pilotSymbols, qpskSymbols.'];

% Add cyclic prefix
dataWithCP = [dataWithPilots(end - cpLength + 1:end), dataWithPilots];

% Reshape and perform IFFT (OFDM modulation)
dataMatrix = reshape(dataWithCP, numSubcarriers, []);
ofdmSignal = ifft(dataMatrix, numSubcarriers);
ofdmSignal1 = reshape(ofdmSignal, 1, []);

% Display
disp("Original Bits:");
disp(bits);
disp("QPSK Symbols:");
disp(qpskSymbols.');
disp("Data with CP and Pilots:");
disp(dataWithCP);
disp("OFDM Signal:");
disp(ofdmSignal1);

%%%%%%%%%%%%%%%%%%%%%%%%%%% Demodulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Reshape back to subcarrier-wise blocks and FFT
ofdmRxMatrix = reshape(ofdmSignal1, numSubcarriers, []);
rxSignal = fft(ofdmRxMatrix, numSubcarriers);

% Remove cyclic prefix
rxSignal1D = reshape(rxSignal, 1, []);
rxSignalNoCP = rxSignal1D(cpLength + 1:end);

% Remove pilots
rxDataSymbols = rxSignalNoCP(numPilotSymbols + 1:end);

% QPSK Demodulation
demodBits = zeros(1, 2*length(rxDataSymbols));
demodBits(1:2:end) = real(rxDataSymbols) > 0;
demodBits(2:2:end) = imag(rxDataSymbols) > 0;

%%%%%%%%%%%%%%%%%%%%%%%%%%% Plotting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

figure(1)
stem(bits);
title("Original Bits");
xlabel("Bit Index"); ylabel("Bit Value");
legend("Original Bits");

figure(2)
hReal = stem(real(ofdmSignal1), 'r', 'DisplayName', 'Real Part');
hold on;
hImag = stem(imag(ofdmSignal1), 'b', 'DisplayName', 'Imaginary Part');
set(hReal, 'Marker', 'o', 'LineWidth', 1.5);
set(hImag, 'Marker', 'x', 'LineWidth', 1.5);
grid on;
title('OFDM Signal (Time Domain)');
xlabel('Sample Index');
ylabel('Amplitude');
legend;
hold off;

figure(3)
stem(demodBits);
title("Demodulated Bits");
xlabel("Bit Index"); ylabel("Bit Value");
legend("Demodulated Bits");

% Optional: Calculate BER
numErrors = sum(bits ~= demodBits);
ber = numErrors / numBits;
fprintf("Bit Error Rate (BER): %.4f\n", ber);



Output

 
 
 
 
 
  
 
 
 

 

MATLAB Code for OFDM Subcarriers (using 16-QAM)

clc;
clear;
close all;

% OFDM System with 16-QAM and Cooley-Tukey FFT/IFFT

% Parameters
N = 64; % Number of OFDM subcarriers
M = 16; % Modulation order (16-QAM -> M = 16)
nSymbols = 100;% Number of OFDM symbols
Ncp = 16; % Length of cyclic prefix

% Generate random data for transmission (0 to M-1 for 16-QAM)
data = randi([0 M-1], nSymbols, N);

% 16-QAM modulation of the data using custom function
modData = zeros(nSymbols, N);
for i = 1:nSymbols
modData(i, :) = qammod(data(i, :), M);
end

% Perform IFFT using Cooley-Tukey to generate the time domain OFDM signal
ofdmTimeSignal = zeros(size(modData));
for i = 1:nSymbols
ofdmTimeSignal(i, :) = ifft(modData(i, :));
end

% Add cyclic prefix
cyclicPrefix = ofdmTimeSignal(:, end-Ncp+1:end); % Extract cyclic prefix
ofdmWithCP = [cyclicPrefix ofdmTimeSignal]; % Add cyclic prefix to the signal

%% Plot Subcarriers in Frequency Domain (before IFFT)
figure;
stem(0:N-1, abs(modData(100, :))); % Plot absolute value of the subcarriers for the first symbol
title('Subcarriers in Frequency Domain for 1st OFDM Symbol (Before IFFT)');
xlabel('Subcarrier Index');
ylabel('Magnitude');

%% Plot Time Domain OFDM Signal (after IFFT)
figure;
plot(real(ofdmTimeSignal(1, :))); % Plot real part of the OFDM time signal for the first symbol
title('OFDM Signal in Time Domain for 1st OFDM Symbol (Without CP)');
xlabel('Time Sample Index');
ylabel('Amplitude');

%% Plot Time Domain OFDM Signal with Cyclic Prefix
figure;
plot(real(ofdmWithCP(1, :))); % Plot real part of the OFDM time signal with CP for the first symbol
title('OFDM Signal in Time Domain for 1st OFDM Symbol (With Cyclic Prefix)');
xlabel('Time Sample Index');
ylabel('Amplitude');

%% Receiver Side - Remove Cyclic Prefix and Demodulate
% Remove cyclic prefix
receivedSignal = ofdmWithCP(:, Ncp+1:end); % Remove cyclic prefix

% Apply FFT using Cooley-Tukey to recover the received subcarriers (back to frequency domain)
receivedSubcarriers = zeros(size(receivedSignal));
for i = 1:nSymbols
receivedSubcarriers(i, :) = fft(receivedSignal(i, :));
end

% 16-QAM Demodulation of the received subcarriers using custom function
receivedData = zeros(nSymbols, N);
for i = 1:nSymbols
receivedData(i, :) = qamdemod(receivedSubcarriers(i, :), M);
end

% Calculate symbol errors
numErrors = sum(data(:) ~= receivedData(:));
fprintf('Number of symbol errors: %d\n', numErrors);

%% Plot Received Subcarriers in Frequency Domain (after FFT at the receiver)
figure;
stem(0:N-1, abs(receivedSubcarriers(100, :))); % Plot absolute value of received subcarriers for the first symbol
title('Received Subcarriers in Frequency Domain for 1st OFDM Symbol (After FFT)');
xlabel('Subcarrier Index');
ylabel('Magnitude');

%% Plot Transmitted Data Constellation (Before IFFT)
figure;
scatterplot(modData(1, :)); % Plot for the first OFDM symbol
title('Transmitted 16-QAM Symbols for 1st OFDM Symbol');
xlabel('In-phase');
ylabel('Quadrature');

%% Plot Received Data Constellation (After Demodulation)
receivedModData = qammod(receivedData(1, :), M); % Map back for plotting
figure;
scatterplot(receivedModData);
title('Received 16-QAM Symbols for 1st OFDM Symbol');
xlabel('In-phase');
ylabel('Quadrature');

 Output

 
















Copy the MATLAB code above from here

 

Read more about

[1] OFDM in details

[2] Structure of an OFDM packet

People are good at skipping over material they already know!

View Related Topics to







Admin & Author: Salim

s

  Website: www.salimwireless.com
  Interests: Signal Processing, Telecommunication, 5G Technology, Present & Future Wireless Technologies, Digital Signal Processing, Computer Networks, Millimeter Wave Band Channel, Web Development
  Seeking an opportunity in the Teaching or Electronics & Telecommunication domains.
  Possess M.Tech in Electronic Communication Systems.


Contact Us

Name

Email *

Message *

Popular Posts

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...

๐Ÿ“˜ Overview of BER and SNR ๐Ÿงฎ Online Simulator for BER calculation of m-ary QAM and m-ary PSK ๐Ÿงฎ MATLAB Code for BER calculation of M-ary QAM, M-ary PSK, QPSK, BPSK, ... ๐Ÿ“š Further Reading ๐Ÿ“‚ View Other Topics on M-ary QAM, M-ary PSK, QPSK ... ๐Ÿงฎ Online Simulator for Constellation Diagram of m-ary QAM ๐Ÿงฎ Online Simulator for Constellation Diagram of m-ary PSK ๐Ÿงฎ MATLAB Code for BER calculation of ASK, FSK, and PSK ๐Ÿงฎ MATLAB Code for BER calculation of Alamouti Scheme ๐Ÿงฎ Different approaches to calculate BER vs SNR What is Bit Error Rate (BER)? The abbreviation BER stands for bit error rate, which indicates how many corrupted bits are received (after the demodulation process) compared to the total number of bits sent in a communication process. It is defined as,  In mathematics, BER = (number of bits received in error / total number of transmitted bits)  On the other hand, SNR ...

RMS Delay Spread, Excess Delay Spread and Multi-path ...

๐Ÿ“˜ Overview of Delay Spread and Multi-path ๐Ÿงฎ Excess Delay spread ๐Ÿงฎ Power delay Profile ๐Ÿงฎ RMS Delay Spread ๐Ÿ“š Further Reading ๐Ÿ“‚ Other Topics on RMS Delay Spread, Excess Delay ... ๐Ÿงฎ Multipath Components or MPCs ๐Ÿงฎ Online Simulator for Calculating RMS Delay Spread ๐Ÿงฎ Why is there significant multipath in the case of very high frequencies? ๐Ÿงฎ Why RMS Delay Spread is essential for wireless communication? ๐Ÿงฎ Why the Power Delay Profile is essential? ๐Ÿงฎ MATLAB Codes for Calculating Different Types of delay Spreads Delay Spread, Excess Delay Spread, and Multipath (MPCs) The fundamental distinction between wireless and wired connections is that in wireless connections signal reaches at receiver thru multipath signal propagation rather than directed transmission like co-axial cable. Wireless Communication has no set communication path between the transmitter and the receiver. The line...

Constellation Diagrams of ASK, PSK, and FSK

๐Ÿ“˜ Overview of Energy per Bit (Eb / N0) ๐Ÿงฎ Online Simulator for constellation diagrams of ASK, FSK, and PSK ๐Ÿงฎ Theory behind Constellation Diagrams of ASK, FSK, and PSK ๐Ÿงฎ MATLAB Codes for Constellation Diagrams of ASK, FSK, and PSK ๐Ÿ“š Further Reading ๐Ÿ“‚ Other Topics on Constellation Diagrams of ASK, PSK, and FSK ... ๐Ÿงฎ Simulator for constellation diagrams of m-ary PSK ๐Ÿงฎ Simulator for constellation diagrams of m-ary QAM BASK (Binary ASK) Modulation: Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1.    BFSK (Binary FSK) Modulation: Transmits one of two signals: +√Eb​ ( On the y-axis, the phase shift of 90 degrees with respect to the x-axis, which is also termed phase offset ) or √Eb (on x-axis), where Eb​ is the energy per bit. These signals represent binary 0 and 1.  BPSK (Binary PSK) Modulation: Transmits one of two signals...

Comparisons among ASK, PSK, and FSK | And the definitions of each

๐Ÿ“˜ Comparisons among ASK, FSK, and PSK ๐Ÿงฎ Online Simulator for calculating Bandwidth of ASK, FSK, and PSK ๐Ÿงฎ MATLAB Code for BER vs. SNR Analysis of ASK, FSK, and PSK ๐Ÿ“š Further Reading ๐Ÿ“‚ View Other Topics on Comparisons among ASK, PSK, and FSK ... ๐Ÿงฎ Comparisons of Noise Sensitivity, Bandwidth, Complexity, etc. ๐Ÿงฎ MATLAB Code for Constellation Diagrams of ASK, FSK, and PSK ๐Ÿงฎ Online Simulator for ASK, FSK, and PSK Generation ๐Ÿงฎ Online Simulator for ASK, FSK, and PSK Constellation ๐Ÿงฎ Some Questions and Answers Modulation ASK, FSK & PSK Constellation MATLAB Simulink MATLAB Code Comparisons among ASK, PSK, and FSK    Comparisons among ASK, PSK, and FSK   Simulator for Calculating Bandwidth of ASK, FSK, and PSK The baud rate represents the number of symbols transmitted per second. Both baud rate and bit rate a...

MATLAB Code for Pulse Amplitude Modulation (PAM) and Demodulation

๐Ÿ“˜ Overview & Theory of Pulse Amplitude Moduation (PAM) ๐Ÿงฎ MATLAB Code for Pulse Amplitude Modulation and Demodulation of Analog Signal and Digital Signal ๐Ÿงฎ Simulation results for comparison of PAM, PWM, PPM, DM, and PCM ๐Ÿ“š Further Reading ๐Ÿ“‚ Other Topics on Pulse Amplitude Modulation ... ๐Ÿงฎ MATLAB Code for Pulse Amplitude Modulation and Demodulation of an Analog Signal (2) ๐Ÿงฎ MATLAB Code for Pulse Amplitude Modulation and Demodulation of Digital data ๐Ÿงฎ Other Pulse Modulation Techniques (e.g., PWM, PPM, DM, and PCM)   Pulse Amplitude Modulation (PAM) & Demodulation of an Analog Message Signal MATLAB Script clc; clear all; close all; fm= 10; % frequency of the message signal fc= 100; % frequency of the carrier signal fs=1000*fm; % (=100KHz) sampling frequency (where 1000 is the upsampling factor) t=0:1/fs:1; % sampling rate of (1/fs = 100 kHz) m=1*cos(2*pi*fm*t); % Message signal with per...

Difference between AWGN and Rayleigh Fading

๐Ÿ“˜ Introduction, AWGN, and Rayleigh Fading ๐Ÿงฎ Simulator for the effect of AWGN and Rayleigh Fading on a BPSK Signal ๐Ÿงฎ MATLAB Codes ๐Ÿ“š Further Reading Wireless Signal Processing Gaussian and Rayleigh Distribution Difference between AWGN and Rayleigh Fading 1. Introduction Rayleigh fading coefficients and AWGN, or additive white gaussian noise [↗] , are two distinct factors that affect a wireless communication channel. In mathematics, we can express it in that way.  Fig: Rayleigh Fading due to multi-paths Let's explore wireless communication under two common noise scenarios: AWGN (Additive White Gaussian Noise) and Rayleigh fading. y = h*x + n ... (i) Symbol '*' represents convolution. The transmitted signal  x  is multiplied by the channel coefficient or channel impulse response (h)  in the equation above, and the symbol  "n"  stands for the white Gaussian noise that is added to the si...

MATLAB Codes for Various types of beamforming | Beam Steering, Digital...

๐Ÿ“˜ How Beamforming Improves SNR ๐Ÿงฎ MATLAB Code ๐Ÿ“š Further Reading ๐Ÿ“‚ Other Topics on Beamforming in MATLAB ... MIMO / Massive MIMO Beamforming Techniques Beamforming Techniques MATLAB Codes for Beamforming... How Beamforming Improves SNR The mathematical [↗] and theoretical aspects of beamforming [↗] have already been covered. We'll talk about coding in MATLAB in this tutorial so that you may generate results for different beamforming approaches. Let's go right to the content of the article. In analog beamforming, certain codebooks are employed on the TX and RX sides to select the best beam pairs. Because of their beamforming gains, communication created through the strongest beams from both the TX and RX side enhances spectrum efficiency. Additionally, beamforming gain directly impacts SNR improvement. Wireless communication system capacity = bandwidth*log2(1+SNR)...

Mathematical Aspects of Beamforming in MIMO

๐Ÿ“˜ Overview ๐Ÿงฎ The Mathematics Behind Analog, Digital, and Hybrid Beamforming ๐Ÿ“š Further Reading ๐Ÿ“‚ Other Topics on Beamforming in MIMO ... MIMO / Massive MIMO Beamforming Techniques Beam steering, which permits strong directed beams towards the receiver to combat excessive pathloss, especially for higher frequency bands, immediately comes to mind when discussing mathematical aspects of Beamforming in MIMO antennas. On the other side, it also lessens signal interference and improves the effectiveness of spatial multiplexing in Massive MIMO communication. Let's go right to the mathematical parts of Beamforming, which will make it easier for you to code in Python and MATLAB. 1. Beam Steering (Analog Beamforming) In the first stage, the BS applies beam steering at the side of the mobile station (MS) while the MS enables omnidirectional transmission. In the following step, the MS uses beam steering while the BS is an...