function [y coeff] = triwave(x,M,duty)
% TRIWAVE
%
%      Finite Fourier Series evaluation of triangle wave
%
%   [y coeff] = triwave(x,M)
%
%      where x are the values to evaluate (-0.5<x<0.5)
%      M is the number of terms to use
%      duty is the relative width of the triangle (compared to period)
%
if (nargin<3)
   duty = 1.0;
end

p = (1:M)';
coeff = sinc(duty*p/2).^2;
c = coeff*ones(size(x));
d = cos(2*pi*p*x);
y = duty*(0.5 + sum(c.*d));
end