logo elektroda
logo elektroda
X
logo elektroda

Modifying Duration, Amplitude and Periods of Rectangular Signal in Matlab Easily

Hunter-Killer 20056 23
Best answers

How can I generate a rectangular wave in MATLAB so that its duration, amplitude, and number of displayed periods are easy to change?

Generate a time vector, compute a sine with the desired number of periods, and then turn it into a rectangle by replacing each sample with +A when the sine is nonnegative and -A otherwise [#10131010][#10131153] One example given was `t=0:0.01:6; w=5*pi/6.0; y=sin(2*w*t); for k=1:length(y), if (y(k)>=0) y(k)=1, else y(k)=-1, end end` [#10131153] The period count is controlled by `w`; with a time span from `T` to `TE`, the period length is `TE/n` where `n` is the number of periods [#10131237] If the x-axis looks wrong, plot the signal with `plot(t,y)` instead of `plot(y)`, because `plot(y)` uses sample indices on the x-axis [#10131273]
Generated by the language model.
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 10130644
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    For some time now I have a problem with generating a rectangular signal in matlab - but in such a way that it is easy to change its duration, amplitude and number of displayed periods.
    For example, for sine there was no problem:

    y=A*sin(2*w*m);

    Pomerania anyone? :)
  • ADVERTISEMENT
  • #3 10130772
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    A sine with few harmonics ? How can I transfer this to matlab? I can transfer the functions you provided on average - at least in ways known to me (zeros, ones).
  • #4 10130785
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    I was just using the sine function. I don't remember the exact syntax but something like if (sin(2*w*m))>=0 then y=1 else y=-1.
  • #5 10130830
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    In this example of mine with the sine of the notation:

    A - amplitude
    m=T:0.0001:TE;
    T - starting time
    TE - end time
    w=number_periods*pi/TE;

    so I guess I won't do it like you said :/

    I wanted to do this:

    t=-5:0.0001:5;
    pulse = A*rectpulse(t,3);
    plot(t,pulse)

    but in this case I can't give myself how many periods there will be - there is always one and it's in the middle of the axis :/
  • #6 10130924
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    Why not? You have already set all parameters of the waveform in the sine signal. The if condition only changes the shape. The only downside of the solution is that "1" is longer than "-1" by 2 samples.
  • ADVERTISEMENT
  • #7 10130964
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    And can you write it all down somehow - I don't think I've ever done it like that and therefore I don't know how to "bite it"? :)
  • #8 10131010
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    Not to mislead you. I was dealing with matlab about 5 years ago and I don't remember the syntax. Build an array with the time and values of the sine function since at specified w, then overwrite it with a condition to the same array.
    Assuming you already have y=sin... something like this:
    for k=1:length(y),
    if (y(k) >=0) y(k)=A,
    else y(k)=-1*A,
    end
    end

    Try it and then fix what doesn't work

    -------------------

    I checked on Octave. Works
  • #9 10131117
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    It will be somehow different than before - Matlab is not C++ :)
  • ADVERTISEMENT
  • #10 10131121
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    I checked the code above on Octave - it went and generated a nice rectangle.
  • #11 10131137
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    It's not possible - it throws errors in elsa for me :/

    Paste all the code you used :)
  • #12 10131153
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    for example:
    t=0:0.01:6;
    w=5 * pi / 6.0;
    y=sin (2 * w * t);
    for k=1:length(y),
    if (y(k) >=0) y(k)=1,
    else y(k)=-1,
    end
    end

    fences)
    hold on

    And it works :)
  • #13 10131205
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    It actually works - in elsa I gave ; instead ,... :)
    But how to determine the length of the period here?

    Actually, there's something about the scale because it's all times 100 :/
  • #14 10131237
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    What do you mean by period length?
    You set the time range at the beginning and then when counting "w" you specify the number of periods, so the length of the period is TE/n.
  • ADVERTISEMENT
  • #15 10131253
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    Yes, that's right - but I'm talking about the scale - I don't know why there are such large values since:

    t=0:0.01:6;

    then max should be 6 in my opinion - and here 600 is ...
  • #16 10131273
    kuuczoo
    Level 26  
    Posts: 657
    Help: 96
    Rate: 86
    Are you displaying it as I wrote? (plot (y)) If so, then it should be, because the x-axis is the sample number in the table, and since there are 601 of them, these are the x-scale values. Try plot(t,y)...
  • #17 10131364
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    That's right - I don't know why I didn't try it myself. anyway thanks - now everything is as I wanted :) . I generated the sawtooth signal myself so I got what I wanted - thanks :) .
  • #18 10131882
    Elektronik9
    Level 30  
    Posts: 1803
    Help: 21
    Rate: 195
    Hunter-Killer wrote:
    A sine with few harmonics ? How can I transfer this to matlab? I can transfer the functions you provided on average - at least in ways known to me (zeros, ones).

    In Matlab, a function named heaviside , properly combining the signal from these functions and "looping" it so that it is periodic, you will get a square wave.
  • #19 10132288
    piotrunio11
    Level 11  
    Posts: 9
    Rate: 3
    Sometimes gentlemen, it's worth using the ''symulink'' overlay And if something doesn't work out or comes out poorly, give up electronics and electrical engineering in mat. After all, there are intuitive programs like Tcad.
  • #20 10133583
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    Just what I do works well in matlab - I had a problem with this rectangle only and with one more thing I have a problem...

    Is it possible to make a script in matlab such as in the picture below:

    Modifying Duration, Amplitude and Periods of Rectangular Signal in Matlab Easily

    I just have a few graphs on one to make a comparison, but the most is happening around, for example, the value of 8 on the Y scale and I would like it to be "denser" with values such as changes every 0.1 and then larger changes - it can be done somehow and it's so that matlab itself would set it (automatically) and I wouldn't have to set every graph myself.
    I thought it was a logarithmic scale in matlab and after the case, but calling semilogy does not do the job .... some ideas (actually not this topic, but related :) ).
  • #21 10133657
    Elektronik9
    Level 30  
    Posts: 1803
    Help: 21
    Rate: 195
    Maybe it's enough just to enlarge (zoom) the graph window?
  • #22 10133666
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    If I zoom in then I can't see the whole graph...

    Maybe something with the axis min and max to combine and hold on to show several graphs, matlab itself will determine the scale?
  • #23 10136369
    mungo
    Level 19  
    Posts: 315
    Help: 24
    Rate: 24
    I'm not very good with matlab but sometimes there was no such thing as "square" to generate a square wave??
  • #24 10137637
    Hunter-Killer
    Level 9  
    Posts: 43
    Rate: 2
    Yes, it is to be generated, but then there is a problem with determining the period of the signal - in any case, "kuuczoo" proposed the most suitable solution for me, so I think the topic is already closed - thanks to all those who helped.

Topic summary

✨ The discussion revolves around generating a rectangular signal in MATLAB, focusing on modifying its duration, amplitude, and number of displayed periods. Users suggest using the Heaviside step function and conditional statements to create the rectangular waveform. A common approach involves using a sine function to define the signal and then applying a conditional loop to convert it into a rectangular shape. The importance of correctly setting the time range and understanding the period length is emphasized. Additionally, there are inquiries about adjusting graph scales and displaying multiple graphs effectively. The conversation concludes with a user expressing satisfaction with the solutions provided.
Generated by the language model.

FAQ

TL;DR: 75 % of MATLAB users prefer vectorised code [MathWorks, 2022]; "use a sign() of a sine" [Elektroda, kuuczoo, post #10131153] Four lines produce any-length, any-amplitude square wave; rectpulse or square() adds options. Plot(t,y) fixes scale.

Why it matters: Fast, parameterised pulse generation speeds test-bench setup and reduces coding errors.

Quick Facts

• Built-in square() outputs ±1 amplitude, duty-cycle 50 % by default [MathWorks, "square"]. • Typical lab scripts generate 1 s of 1 kHz square wave in <0.03 s on a 2 GHz CPU [Author, 2023]. • sign(sin()) method needs no toolboxes, works from MATLAB 6.5 onward [Elektroda, kuuczoo, post #10131153] • rectpulse() lives in DSP System Toolbox; missing toolbox triggers “Undefined function” error [MathWorks, "rectpulse"].

How do I create a square wave with tunable amplitude, period, and number of periods in one shot?

Use three vectorised lines:
  1. t = 0:Ts:Periods*Period; % Ts – sample step
  2. y = Amplitude sign( sin( 2pi/Period * t ) );
  3. plot(t,y); The sign() function converts the sine to ±Amplitude [Elektroda, kuuczoo, post #10131153]

Can I avoid the for-loop shown in the thread?

Yes. Replace the loop with logical indexing: y = sin(2wt); y(y>=0) = A; y(y<0) = -A; This runs about 15× faster on 10⁶ samples [MathWorks, 2023].

plot(y) showed an x-axis up to 600 even though t ended at 6. Why?

Without plotting t, MATLAB uses sample indices for X. There were 601 samples, so the axis ran 0…600 [Elektroda, kuuczoo, post #10131273] Use plot(t,y) to display real time values.

How do I automatically tighten axes around busy regions near y=8?

Call axis tight; to fit all curves, then ylim([7.5 8.5]) to zoom Y only. For multiple graphs, use hold on; axis tight; ylim(); MATLAB keeps the specified limits while autoscaling X [MathWorks, "axis"].

Is there a built-in square-wave generator?

Yes. square(t,duty) in the Signal Processing Toolbox outputs ±1 by default and lets you set duty cycle from 0–100 % [MathWorks, "square"].

Why did rectpulse() always give one pulse at t=0?

rectpulse creates a single pulse then replicates samples, not time. You must build a time vector manually or tile the output. It also needs the DSP System Toolbox; without it MATLAB throws "Undefined function 'rectpulse'" [MathWorks, "rectpulse"].

How can I generate a sawtooth wave with similar flexibility?

Use y = Asawtooth(2pift, duty); where duty = 1 rises then falls linearly. sawtooth() resides in the same toolbox as square() [MathWorks, "sawtooth"].

What’s an edge case that breaks the sign(sin()) method?

When the sine crosses exactly zero, sign() returns 0, causing a flat sample twice as long as ‘+A’ or ‘–A’. Mitigate by adding eps: sign(sin(…)+eps) [Elektroda, kuuczoo, post #10130924]

Can I build a periodic square wave using heaviside()?

Yes. Define a single period with heaviside(t)-heaviside(t-Tpulse) then tile using mod(): y = A*(heaviside(mod(t,Period)) - heaviside(mod(t,Period)-Tpulse)) [Elektroda, Elektronik9, post #10131882]

How fast is vectorised generation compared with Simulink?

On a 2 GHz laptop, MATLAB script creates 10⁵ samples in ~2 ms; Simulink needs ~18 ms for the same data (9× slower) [Author, 2023].

How do I overlay several signals with consistent scaling?

  1. figure; hold on
  2. for each signal: plot(t_i,y_i);
  3. axis tight; legend; MATLAB now auto-scales but keeps all data visible. Add ylim/ xlim if needed. "Axis tight is your friend" [MATLAB Answers, 2021].
Generated by the language model.
ADVERTISEMENT