code for generating triangular waveform in matlab

Discussion in 'General Electronics Chat' started by sadaf, Jan 28, 2012.

  1. sadaf

    Thread Starter New Member

    Aug 4, 2010
    25
    0
    Hello!
    Kindly tell me that what is the code for generating a triangular waveform in matlab. . .?
    i am new in matlab............
     
  2. PaulEE

    Member

    Dec 23, 2011
    423
    32
    A triangular wave is simply alternating lines with positive and negative slopes between upper and lower limits.

    I haven't programmed matlab in awhile, but I envision nested while loops, one overall loop for the number of periods of the wave, one for the "up" line, and one for the "down" line...something like this:
    Code ( (Unknown Language)):
    1.  
    2. while(i=0; i<periods; i++){
    3.  
    4. while(j=lowerLimit; j<upperLimit; j++)
    5. {
    6.      answerMatrix[length(answerMatrix) + 1] = upperLimit;
    7. }
    8. while(k=upperLimit; k>lowerLimit; k--)
    9. {
    10.      answerMatrix[length(answerMatrix) + 1] = lowerLimit;
    11. }
    12.  
    13. }
    14.  
    15.  
    I'm not saying that this will compile, but it's probably one way to do it.
     
  3. MrChips

    Moderator

    Oct 2, 2009
    12,423
    3,359
    You have to be more specific than this.

    Do you want an array of increasing and decreasing numbers or do you want an electrical signal coming from loudspeaker or the line out jack?

    What is the amplitude, period and sampling frequency?

    To generate an array with the numbers from 0 to 9, simply write:

    x = [0:9]

    To generate an array with the numbers from 10 to 1:

    y = [10:-1:1]

    To concatenate the two arrays:

    z = [ x y]


    You can write this all in one line:

    z = [ [0:9] [10:-1:1] ]

    As you can see, this is a lot easier than C.
     
  4. sadaf

    Thread Starter New Member

    Aug 4, 2010
    25
    0
    no no..............
    i think u don't get my question.....
    i just want to ask that.....
    as we write for sawtooth wave
    y=A*sawtooth(t)
    so i just asking about the notation of triangular wave
     
  5. holnis

    Member

    Nov 25, 2011
    50
    4
    I think you're talking about the function fs_tri(N) it is a function that accept number of harmonics, n as input and produce the Fourier series waveform up to and included n harmonics, it can be implemented as follow:

    function fs_tri(N)
    x = linspace(0, 10);
    f = ones(1,100)*pi;
    for i = 1:N
    b = -2/i;
    f = f + b*sin(i*x);
    end
    plot(x,f)
     
  6. sadaf

    Thread Starter New Member

    Aug 4, 2010
    25
    0
    i got it..........
    it is
    y=A*sawtooth(t,o.5)
    this is to plot triangular wave
     
Loading...