How to create periodic square wave signals with custom frequency, amplitude, and duty cycle using MATLAB?
John Michell answered .
2026-07-24
Use the square() function from Signal Processing Toolbox:
fs = 1000; % Sampling frequency (Hz)
t = 0:1/fs:1; % Time vector for 1 second
freq = 5; % 5 Hz Square wave
duty_cycle = 50; % 50% duty cycle
% Generate square wave (-1 to +1)
sq_wave = square(2*pi*freq*t, duty_cycle);
figure;
plot(t, sq_wave, 'LineWidth', 2);
grid on;
ylim([-1.5 1.5]);
title('5 Hz Square Wave Signal');
xlabel('Time (sec)'); ylabel('Amplitude');