how to generate square wave in matlab

560 views (last 30 days)
I intend to generate a square wave with respect to time by following characteristic:
I want to generate square-wave force demand of 1 KN at 10 Hz. That means amplitude will be between 0 to 1000 and time will be between 0 to 1 (sec) with .1 interval.
Please someone help me.

Accepted Answer

Image Analyst
Image Analyst on 16 Jun 2014
Edited: Image Analyst on 24 Nov 2020
Make one period, then use repmat() to replicate as many times as you want.
% Now make one cycle with amplitude 1000 and 200 elements.
onePeriod = 1000 * [ones(1, 100), zeros(1, 100)];
% 200 elements is supposed to be 0.1 seconds so find out delta t.
dt = 0.1 / numel(onePeriod);
% Define number of cycles.
numCycles = 10;
% Copy this period that many times.
fullWaveForm = repmat(onePeriod, [1, numCycles]);
% Make time axis from 0 to 1 second.
t = dt * (0 : (numel(fullWaveForm) - 1));
% Now plot it.
plot(t, fullWaveForm, 'b-', 'LineWidth', 2);
FontSize = 20;
xlabel('Time (seconds)', 'FontSize', FontSize);
ylabel('Amplitude', 'FontSize', FontSize);
title('Square Wave With 10 Cycles', 'FontSize', FontSize);
grid on;
Image Analyst
Image Analyst on 15 Jun 2017
I don't know what that means. What is a "saturation block"? Is that Simulink? The poster said "in matlab" but if your function is for Simulink, then perhaps your post will help Simulink users.

Sign in to comment.

More Answers (4)

Rashmil Dahanayake
Rashmil Dahanayake on 16 Jun 2014

Bill Tubbs
Bill Tubbs on 26 Mar 2020
Based on Rashmil Dahanayake's idea I made a simple function to generate regular square waves for discrete time.
function sq = square_dt(n,period)
% Square wave in discrete time
repeats = n/period;
sq = square(2*pi*linspace(0,repeats-1/n,n));
(Works best when period is an even number)
>> square_dt(10,4)
ans =
1 1 -1 -1 1 1 -1 -1 1 1
If you want only the positive cycles, modify the code like Rashmil's:
function sq = square_dtp(n,period)
% Square wave in discrete time
repeats = n/period;
sq = (square(2*pi*linspace(0,repeats-1/n,n))+1)/2;
>> square_dtp(10,4)
ans =
1 1 0 0 1 1 0 0 1 1

udhaya ram  mohan
udhaya ram mohan on 18 Oct 2016
i need to generate the square wave with positive cycle only please send me a code for it
  1 Comment
Walter Roberson
Walter Roberson on 18 Oct 2016
Rashmil Dahanayake's Answer already only generates positive values.

Sign in to comment.

pisini padmaja
pisini padmaja on 23 Nov 2020
Edited: Image Analyst on 24 Nov 2020
%square function%
clear all;
close all;
title('square signal 318126512095');
title('square sequence 318126512095');
Vedanta Mohapatra
Vedanta Mohapatra on 1 Oct 2021
You have to use signum to generate some sort of square wave

Sign in to comment.


Find more on Signal Generation and Preprocessing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by