Skip to main content
Home Wireless Communication Modulation MATLAB Beamforming Project Ideas MIMO Computer Networks Lab 🚀

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

 

 

Another Example

clc;
clear;
close all;

% Main script
bitsLength = 128;
subcarriers = 64;
cpLength = 8;

bits = generateRandomBits(bitsLength);
txSignal = OFDMTransmitter(bits, subcarriers, cpLength);
rxSignal = OFDMReceiver(txSignal, subcarriers, cpLength);

Fs = 100; % Sampling frequency
[transmittedSignal, transmittedTime] = representDigitalSignal(bits, Fs);
[receivedSignal, receivedTime] = representDigitalSignal(rxSignal, Fs);

plotSignal(transmittedTime, transmittedSignal, 'Transmitted Bits');
plotSignal(receivedTime, receivedSignal, 'Received Bits');

% Plot OFDM Modulated Signal
figure;
subplot(2,1,1);
plot(real(txSignal));
title('OFDM Modulated Signal - Real Part');
xlabel('Sample');
ylabel('Amplitude');

subplot(2,1,2);
plot(imag(txSignal));
title('OFDM Modulated Signal - Imaginary Part');
xlabel('Sample');
ylabel('Amplitude');

% Function to generate random bits
function bits = generateRandomBits(length)
    bits = randi([0 1], 1, length);
end

% Function to perform FFT
function spectrum = myfft(signal)
    N = length(signal);
    if N <= 1
        spectrum = signal;
        return;
    end

    even = signal(1:2:end);
    odd = signal(2:2:end);

    evenFFT = myfft(even);
    oddFFT = myfft(odd);

    spectrum = zeros(1, N);
    for k = 1:N/2
        angle = -2 * pi * (k-1) / N;
        cosAngle = cos(angle);
        sinAngle = sin(angle);

        oddPart = oddFFT(k) * (cosAngle - 1i * sinAngle);
        spectrum(k) = evenFFT(k) + oddPart;
        spectrum(k + N/2) = evenFFT(k) - oddPart;
    end
end

% Function to perform IFFT
function signal = myifft(spectrum)
    conjugateSignal = conj(spectrum);
    fftResult = myfft(conjugateSignal);
    signal = conj(fftResult) / length(conjugateSignal);
end

% Function for OFDM Transmitter
function txSignal = OFDMTransmitter(bits, N, cpLength)
    symbols = zeros(1, length(bits)/2);
    for i = 1:2:length(bits)
        realPart = bits(i) * 2 - 1;
        imagPart = bits(i+1) * 2 - 1;
        symbols((i+1)/2) = realPart + 1i * imagPart;
    end

    parallelSymbols = reshape(symbols, N, []);
    timeDomainSignal = zeros(size(parallelSymbols));

    for i = 1:size(parallelSymbols, 2)
        timeDomainSignal(:, i) = myifft(parallelSymbols(:, i));
    end

    txSignal = [];
    for i = 1:size(timeDomainSignal, 2)
        cp = timeDomainSignal(end-cpLength+1:end, i);
        txSignal = [txSignal; cp; timeDomainSignal(:, i)];
    end
end

% Function for OFDM Receiver
function receivedBits = OFDMReceiver(rxSignal, N, cpLength)
    numSymbols = floor(length(rxSignal) / (N + cpLength));
    removedCP = zeros(N, numSymbols);

    for i = 1:numSymbols
        symbolStart = (i-1) * (N + cpLength) + cpLength + 1;
        removedCP(:, i) = rxSignal(symbolStart:symbolStart + N - 1);
    end

    frequencyDomainSignal = zeros(size(removedCP));
    for i = 1:size(removedCP, 2)
        frequencyDomainSignal(:, i) = myfft(removedCP(:, i));
    end

    receivedBits = zeros(1, numel(frequencyDomainSignal) * 2);
    index = 1;
    for i = 1:numel(frequencyDomainSignal)
        realPart = real(frequencyDomainSignal(i));
        imagPart = imag(frequencyDomainSignal(i));
        receivedBits(index) = realPart >= 0;
        receivedBits(index + 1) = imagPart >= 0;
        index = index + 2;
    end
end

% Function to represent digital signal for plotting
function [bitRepresentation, timeInstances] = representDigitalSignal(bits, Fs)
    bitRepresentation = zeros(1, Fs * length(bits));
    for n = 1:length(bits)
        if bits(n) == 1
            bitRepresentation((n-1)*Fs+1:n*Fs) = 1;
        else
            bitRepresentation((n-1)*Fs+1:n*Fs) = 0;
        end
    end
    timeInstances = (0:Fs*length(bits)-1) / Fs;
end

% Function to plot the signal
function plotSignal(timeInstances, signal, label)
    figure;
    plot(timeInstances, signal);
    title(label);
    xlabel('Time');
    ylabel('Amplitude');
end


Output

 
 
 
 
 
  
 
 
 

Copy the MATLAB Code above from here

 

 

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

profile

  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 ASK, FSK, and PSK

  BER vs. SNR denotes how many bits in error are received in a communication process for a particular Signal-to-noise (SNR) ratio. In most cases, SNR is measured in decibel (dB). For a typical communication system, a signal is often affected by two types of noises 1. Additive White Gaussian Noise (AWGN) 2. Rayleigh Fading In the case of additive white Gaussian noise (AWGN), random magnitude is added to the transmitted signal. On the other hand, Rayleigh fading (due to multipath) attenuates the different frequency components of a signal differently. A good signal-to-noise ratio tries to mitigate the effect of noise.  Calculate BER for Binary ASK Modulation The theoretical BER for binary ASK (BASK) in an AWGN channel is given by: BER  = (1/2) * erfc(0.5 * sqrt(SNR_ask));   Enter SNR (dB): Calculate BER BER vs. SNR curves for ASK, FSK, and PSK Calculate BER for Binary FSK Modulation The theoretical BER for binary FSK (BFSK) in an AWGN channel is g

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

Modulation Constellation Diagrams BER vs. SNR BER vs SNR for M-QAM, M-PSK, QPSk, BPSK, ... 1. 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 refers to the signal-to-noise power ratio. For ease of calculation, we commonly convert it to dB or decibels.   2. What is Signal the signal-to-noise ratio (SNR)? SNR = signal power/noise power (SNR is a ratio of signal power to noise power) SNR (in dB) = 10*log(signal power / noise power) [base 10] For instance, the SNR for a given communication system is 3dB. So, SNR (in ratio) = 10^{SNR (in dB) / 10} = 2 Therefore, in this instance, the signal power i

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

Signal Processing RMS Delay Spread, Excess Delay Spread, and Multipath... RMS 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 of sight path, also known as the LOS path, is the shortest and most direct communication link between TX and RX. The other communication pathways are called non-line of sight (NLOS) paths. Reflection and refraction of transmitted signals with building walls, foliage, and other objects create NLOS paths. [ Read More about LOS and NLOS Paths] Multipath Components or MPCs: The linear nature of the multipath component signals is evident. This signifies that one multipath component signal is a scalar multiple of

Difference between AWGN and Rayleigh Fading

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.  Let's explore wireless communication under two common noise scenarios: AWGN (Additive White Gaussian Noise) and Rayleigh fading. y = hx + n ... (i) 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 signal through any type of channel (here, it is a wireless channel or wireless medium). Due to multi-paths the channel impulse response (h) changes. And multi-paths cause Rayleigh fading. 2. Additive White Gaussian Noise (AWGN) The mathematical effect involves adding Gauss

FFT Magnitude and Phase Spectrum using MATLAB

  MATLAB Code  % Developed by SalimWireless.Com clc; clear; close all; % Configuration parameters fs = 10000; % Sampling rate (Hz) t = 0:1/fs:1-1/fs; % Time vector creation % Signal definition x = sin(2 * pi * 100 * t) + cos(2 * pi * 1000 * t); % Calculate the Fourier Transform y = fft(x); z = fftshift(y); % Create frequency vector ly = length(y); f = (-ly/2:ly/2-1) / ly * fs; % Calculate phase while avoiding numerical precision issues tol = 1e-6; % Tolerance threshold for zeroing small values z(abs(z) < tol) = 0; phase = angle(z); % Plot the original Signal figure; subplot(3, 1, 1); plot(t, x, 'b'); xlabel('Time (s)'); ylabel('|y|'); title('Original Messge Signal'); grid on; % Plot the magnitude of the Fourier Transform subplot(3, 1, 2); stem(f, abs(z), 'b'); xlabel('Frequency (Hz)'); ylabel('|y|'); title('Magnitude of the Fourier Transform'); grid on; % Plot the phase of the Fourier Transform subplot(3, 1, 3); stem(f,

Constellation Diagrams of ASK, PSK, and FSK

Modulation ASK, FSK & PSK Constellation 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: +√Eb​ or -√Eb (they differ by 180 degree phase shift), where Eb​ is the energy per bit. These signals represent binary 0 and 1.  This article will primarily discuss constellation diagrams, as well as what constellation diagrams tell us and the significance of constellation diagrams. Constellation diagrams can often demonstrate how the amplitude and phase of signals or symbols differ. These two characteristics lessen the interference between t

BER performance of QPSK with BPSK, 4-QAM, 16-QAM, 64-QAM, 256-QAM, etc

   Compare the BER performance of QPSK with other modulation schemes (e.g.,  BPSK, 4-QAM, 16-QAM, 64-QAM, 256-QAM, etc) under similar conditions. MATLAB Code clear all; close all; % Set parameters for QAM snr_dB = -20:2:20; % SNR values in dB qam_orders = [4, 16, 64, 256]; % QAM modulation orders % Loop through each QAM order and calculate theoretical BER figure; for qam_order = qam_orders     % Calculate theoretical BER using berawgn for QAM     ber_qam = berawgn(snr_dB, 'qam', qam_order);     % Plot the results for QAM     semilogy(snr_dB, ber_qam, 'o-', 'DisplayName', sprintf('%d-QAM', qam_order));     hold on; end % Set parameters for QPSK EbNoVec_qpsk = (-20:20)'; % Eb/No range for QPSK SNRlin_qpsk = 10.^(EbNoVec_qpsk/10); % SNR linear values for QPSK % Calculate the theoretical BER for QPSK using the provided formula ber_qpsk_theo = 2*qfunc(sqrt(2*SNRlin_qpsk)); % Plot the results for QPSK semilogy(EbNoVec_qpsk, ber_qpsk_theo, 's-', &#

Channel Impulse Response (CIR)

Channel Impulse Response (CIR) Wireless Signal Processing CIR, Doppler Shift & Gaussian Random Variable  The Channel Impulse Response (CIR) is a concept primarily used in the field of telecommunications and signal processing. It provides information about how a communication channel responds to an impulse signal.   What is the Channel Impulse Response (CIR) ? It describes the behavior of a communication channel in response to an impulse signal. In signal processing,  an impulse signal has zero amplitude at all other times and amplitude  ∞ at time 0 for the signal. Using a Dirac Delta function, we can approximate this.  ...(i) δ( t) now has a very intriguing characteristic. The answer is 1 when the Fourier Transform of  δ( t) is calculated. As a result, all frequencies are responded to equally by  δ (t). This is crucial since we never know which frequencies a system will affect when examining an unidentified one. Since it can test the system for all freq