make a square wave in matlab

To generate a square wave in MATLAB, one can use the square function. The square function generates a square wave with a 50% duty cycle by default.

main.m
% Generate a square wave with a 50% duty cycle
t = linspace(0, 1, 1000);   % Time vector
f = 5;                      % Frequency of the square wave
x = square(2*pi*f*t);       % Generate a square wave
plot(t, x);                 % Plot the square wave
252 chars
6 lines

This will generate a square wave with a frequency of 5 Hz and a 50% duty cycle.

If you want to change the duty cycle of the square wave, you can specify it as a second argument to the square function. For example, to generate a square wave with a 25% duty cycle:

main.m
% Generate a square wave with a 25% duty cycle
t = linspace(0, 1, 1000);   % Time vector
f = 5;                      % Frequency of the square wave
duty_cycle = 25;            % Duty cycle of the square wave
x = square(2*pi*f*t, duty_cycle);    % Generate a square wave
plot(t, x);                 % Plot the square wave
321 chars
7 lines

This will generate a square wave with a frequency of 5 Hz and a 25% duty cycle.

related categories

gistlibby LogSnag