why the square wave is just a line?

2 views (last 30 days)
ocsse
ocsse on 25 Mar 2018
Commented: Jan on 25 Mar 2018
i'm trying to get a square wave graph for 5 cycles. but the plot is just a line
T = 2.25;
samples = 500;
t = linspace(-2.75,T,samples+1); % 5 cycles
t(end) = [];
s(-2.75 <= t < -0.25) = 1;
s(-0.25 <= t < 2.25) = -1;
N = 5;
s = repmat(s, [1 N]);
t = linspace(-2.75, N*T, N*samples + 1);
t(end) = [];
figure()
plot(t, s)
thanks

Accepted Answer

Star Strider
Star Strider on 25 Mar 2018
You can only do paired comparisons. Break the logic up into two separate conditions and it works:
s(-2.75 <= t & t < -0.25) = 1;
s(-0.25 <= t & t < 2.25) = -1;
  3 Comments
Star Strider
Star Strider on 25 Mar 2018
As always, my pleasure!
Jan
Jan on 25 Mar 2018
@Star Strider: You gave your answer 10 minutes before I posted my one. I'm sure that I've pressed the Reload button directly before starting to type my answer, but I did not see yours. It took me a minute to type. This means that it takes about 9 minutes until I can see a given answer.
I had this impression repeatedly in the last months, that I've posted answers, which have been given already but have not been visible for me. It looks a little bit awkward, like a parrot. I'm going to ask a question, if somebody else share this experience.

Sign in to comment.

More Answers (1)

Jan
Jan on 25 Mar 2018
The problem is here:
s(-2.75 <= t < -0.25) = 1;
s(-0.25 <= t < 2.25) = -1;
The condition -2.75 <= t < -0.25 is evaluated from left to right:
  1. tmp = -2.75 <= t: This is either FALSE (0) or TRUE (1)
  2. tmp < -0.25: This is FALSE in every case, because neither 0 nor 1 are lower than -0.25.
You want:
s(-2.75 <= t & t < -0.25) = 1;
s(-0.25 <= t & t < 2.25) = -1;

Categories

Find more on Startup and Shutdown 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!