MATLAB Code
>> %% OFDM BPSK Full Simulation: All Plots
clear all; close all; clc;
% --- 0. Parameters (Matching your HTML UI) ---
nSymbols = 2; % Number of OFDM Symbols
N = 4; % Subcarriers
nCP = 2; % Cyclic Prefix
fs = 1000; % Sampling Frequency (Hz)
fc = 5; % Carrier Frequency (Hz)
baudRate = 1; % Baud Rate
%% --- 1. Generate Message (Bitstream) ---
totalBits = nSymbols * N;
bits = randi([0 1], 1, totalBits);
%% --- 2. Make OFDM Symbols (Serial to Parallel) ---
% Each column is one OFDM Symbol
bitMatrix = reshape(bits, N, nSymbols);
%% --- 3. Apply BPSK Mapping ---
% 0 -> -1, 1 -> 1
bpskSymbols = 2*bitMatrix - 1;
%% --- 4. Perform IFFT (Baseband Time Domain) ---
ofdmTimeDomain = ifft(bpskSymbols, N);
%% --- 5. Add Cyclic Prefix ---
cpPart = ofdmTimeDomain(end-nCP+1:end, :);
ofdmWithCP = [cpPart; ofdmTimeDomain];
serialBaseband = ofdmWithCP(:); % Flatten for transmission
%% --- 6. Generate Passband Signal ---
T_sample = 1 / baudRate;
total_duration = length(serialBaseband) * T_sample;
t = 0 : 1/fs : total_duration - (1/fs);
passbandSignal = zeros(size(t));
for i = 1:length(serialBaseband)
t_idx = (t >= (i-1)*T_sample) & (t < i*T_sample);
I = real(serialBaseband(i));
Q = imag(serialBaseband(i));
passbandSignal(t_idx) = I*cos(2*pi*fc*t(t_idx)) - Q*sin(2*pi*fc*t(t_idx));
end
%% --- VISUALIZATION (All Lab Plots) ---
figure('Name', 'OFDM BPSK Full Simulation Flow', 'Color', 'w', 'Position', [50, 50, 1000, 900]);
% Plot 1: Input Bitstream
subplot(5,1,1);
stairs([bits, bits(end)], 'LineWidth', 2, 'Color', 'b');
ylim([-0.5 1.5]); grid on;
title('Step 1: Input Binary Bitstream (Serial)');
xlabel('Bit Index'); ylabel('Logic');
% Plot 2: OFDM Symbol Mapping (Parallel)
subplot(5,1,2);
imagesc(1:nSymbols, 1:N, bitMatrix);
colormap([1 1 1; 0 0 0]); % White for 0, Black for 1
set(gca, 'YDir', 'normal', 'XTick', 1:nSymbols, 'YTick', 1:N);
title('Step 2: Parallel OFDM Symbol Mapping (Matrix View)');
xlabel('OFDM Symbol #'); ylabel('Subcarrier Index');
colorbar('Ticks', [0, 1], 'TickLabels', {'Bit 0', 'Bit 1'});
% Plot 3: BPSK Symbols
subplot(5,1,3);
stem(bpskSymbols(:), 'filled', 'm', 'LineWidth', 1.5);
ylim([-1.5 1.5]); grid on;
title('Step 3: BPSK Mapped Symbols (-1 or 1)');
xlabel('Serial Index'); ylabel('Amplitude');
% Plot 4: IFFT Output (Baseband Time Domain with CP)
subplot(5,1,4);
plot(real(serialBaseband), '-o', 'LineWidth', 1.5); hold on;
plot(imag(serialBaseband), '-s', 'LineWidth', 1.5);
grid on;
title('Step 4 & 5: Time Domain Samples (After IFFT & CP)');
legend('Real (I)', 'Imag (Q)');
xlabel('Sample Index');
% Plot 5: Passband Signal
subplot(5,1,5);
plot(t, passbandSignal, 'Color', [0.85 0.33 0.1]);
grid on;
title(['Step 6: Final Passband OFDM Signal (Carrier: ', num2str(fc), ' Hz)']);
xlabel('Time (seconds)'); ylabel('Amplitude');
sgtitle('OFDM Modulation: From Source Bits to Passband Signal', 'FontSize', 14, 'FontWeight', 'bold');