MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# Help with plotting triangular wave

Asked by David on 29 Dec 2012

Hi guys. I am struggling with a homework question.

*A triangular wave with period T may be written as: 1/(2n+1)^2 * cos((2n+1)*w0*t) (this is a series, n starts at 0 and goes on until infinity). where w0 = 2pi/T. This wave form is sampled, with a sampling time of TS = T/200, to yield the sampled signal x(n).

Use MATLAB to demonstrate how the series converges to the triangular wave.

Generate a plot(properly labelled) with 6, 10 and 30 terms for a value of T = 2.*

The code i inputted into matlab is

t=2; Ts=t/200; w=(2*pi)/t; n=0:9999; x=((2*n+1).^-2).*(cos((2*n+1)*w*Ts)); plot(x)

When i plot this it doesn't give a triangular wave. I must have done something wrong or missed a detail. Any help would be appreciated.

Thank you very much

## Products

No products are associated with this question.

Answer by Matt J on 29 Dec 2012
Edited by Matt J on 29 Dec 2012
• You evaluate x(t) only at a single point t=Ts. You're supposed to evaluate at many sampling times, t, spaced apart by Ts.
• You haven't summed over n.
• You will make life easier on yourself (and on us, and on your graders) if you define T, Ts, and t in your code the same way as the homework exercise defines them. Instead, your code changes T to t.

David on 1 Jan 2013

Using this code i do get a triangular wave but when i plot for n=10,30 terms the graph doesn't really change much.

```n=0;
T=2;
Ts=T/200;
t=-T/2 : Ts : T/2;
w=(2*pi)/T;
s = 0;
for n = 0 : 5
s = s + ((2*n+1)^-2) * (cos((2*n+1)*w*t));
end
plot(t,s)
```

Is this the correct code to demonstrate how the series converges to a triangular wave? and do i just use new number of n terms to complete question 2?

I really do appreciate the help

Image Analyst on 1 Jan 2013

Try it like this:

```n=0;
T=2;
Ts=T/200;
t=-T/2 : Ts : T/2;
w=(2*pi)/T;
s = 0;
figure;
maxTerms = 6; % also use 10 and 30
for n = 0 : maxTerms - 1
s = s + ((2*n+1)^-2) * (cos((2*n+1)*w*t));
end
% Make wave start at 0
s = s - s(1);
plot(t,s)
grid on;
hold on;
maxTerms = 10;
for n = 0 : maxTerms - 1
s = s + ((2*n+1)^-2) * (cos((2*n+1)*w*t));
end
% Make wave start at 0
s = s - s(1);
plot(t,s)
maxTerms = 30;
for n = 0 : maxTerms - 1
s = s + ((2*n+1)^-2) * (cos((2*n+1)*w*t));
end
% Make wave start at 0
s = s - s(1);
plot(t,s)
```
Matt J on 1 Jan 2013

Using this code i do get a triangular wave but when i plot for n=10,30 terms the graph doesn't really change much.

Looks fine to me. The difference between nmax=10 and nmax=30 is subtle, but I still do see a noticeable sharpening of the triangle. At some point, i.e., as convergence occurs, it is supposed to stop changing. visibly