Results 1 to 2 of 2

Math Help - Plotting a square wave using MATLAB

  1. #1
    MHF Contributor alexmahone's Avatar
    Joined
    Oct 2008
    Posts
    1,074
    Thanks
    7

    Plotting a square wave using MATLAB

    The following MATLAB code plots a square wave.

    Code:
    x=linspace(-4*pi,4*pi,1000);
    
    for i=1:125
        y(i)=1;
    end
    for i=125:250
        y(i)=-1;
    end
    for i=250:375
        y(i)=1;
    end
    for i=375:500
        y(i)=-1;
    end
    for i=500:625
        y(i)=1;
    end
    for i=625:750
        y(i)=-1;
    end
    for i=750:875
        y(i)=1;
    end
    for i=875:1000
        y(i)=-1;
    end
    
    plot(x,y)
    axis([-4*pi 4*pi -2 2])
    xlabel('x')
    ylabel('Square wave')
    I have attached the output. I am curious to know why MATLAB plots those vertical lines although I didn't ask it to.
    Attached Thumbnails Attached Thumbnails Plotting a square wave using MATLAB-square.png  
    Follow Math Help Forum on Facebook and Google+

  2. #2
    Super Member ILikeSerena's Avatar
    Joined
    Dec 2011
    Posts
    733
    Thanks
    121

    Re: Plotting a square wave using MATLAB

    It's not really a square wave.
    It's a number of dots that belong to a square wave.
    Furthermore those lines are not vertical.
    You have for instance y(124)=1 and y(125)=-1.
    Matlab connects all the dots with lines, and these 2 dots are connected with an almost vertical line.
    Follow Math Help Forum on Facebook and Google+

Similar Math Help Forum Discussions

  1. Replies: 2
    Last Post: January 3rd 2012, 11:53 AM
  2. matlab plotting graph need help
    Posted in the Math Software Forum
    Replies: 1
    Last Post: August 7th 2010, 12:27 AM
  3. Matlab - Plotting Circles
    Posted in the Math Software Forum
    Replies: 1
    Last Post: February 16th 2009, 09:28 AM
  4. MATLAB: Plotting MATRIX?
    Posted in the Math Software Forum
    Replies: 3
    Last Post: January 25th 2009, 01:21 PM
  5. MATLAB - plotting a quadratic
    Posted in the Math Software Forum
    Replies: 2
    Last Post: June 15th 2008, 06:25 PM

Search Tags


/mathhelpforum @mathhelpforum