How do I create a square wave using 'zeros' and 'ones' functions?

Here is my code so far.
clear all; close all; clc;
incrm = 0.01;
T0 = 2;
W0 = pi;
t = 0:0.01:10;
xt = ???????????????
plot(t,xt)
hold on
xlim([0,10]);
ylim([0,1]);
xlabel('t');
ylabel('xt');
title('Signal Approximation')

 Accepted Answer

Edited
t = 0:0.01:10;
x=ones(1,numel(t)) %add this
x(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10 )=0 %and this
plot(t,x) % if you add t+pi horizontal shift or t-pi
xlim([0,10]);
ylim([0,1]);
xlabel('t');
ylabel('xt');
title('Signal Approximation')

20 Comments

use builtin square() to create square wave
I have to do it using 'zeros' and 'ones' functions!
That didn't work. It gave me all zeros in my plot. (The second image I sent.) I need it to look like the first image I sent.
See the edited answer and attached screenshot now
if its what you want accept the answer so people know question is solved
upload the code you are trying
dude ! change
x(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10 )=0
to this
xt(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10 )=0
I noticed that and changed it and it still isn't working.
x(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10 )=0 <----- it should be zero not one!!!
YES!!! It's working now! Thank you
Anytime ,if it works accept the answer
Is there a way to do it with a combination of the zeros and ones functions?

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!