MATLAB: Write a function called triangle_wave

looptriangular wave

The function computes the sum Σ((−1^k)*sin((2k+1)(t))/((2k+1)^2)) for each of 1001 values of t uniformly spaced from 0 to 4π inclusive. The input argument is a scalar non-negative integer n, and the output argument is a row vector of 1001 such sums—one sum for each value of t. You can test your function by calling it with n == 20 or greater and plotting the result and you will see why the function is called “triangle_wave”.
For this question, I have written a function to solve it but my code is always rejected by the grader.
This is the plot I get whenever I plot my function;
My attempt made use of a nested for loop as shown:
Please any clue to get my code right will be highly appreciated. Thanks

Best Answer

Do you have any useful details about the "rejection of the grader"? Is this a Cody Coursework? I start to detest this, because many students struggle with the automatic rejection without useful information. I do not believe in automatic teaching.
Perhaps it matters than 4*pi is not 12.5664. Try:
m = linspace(0, 4*pi, 1001)
You have to reset sump to 0 for each time point. Move the sump = 0 inside the for t loop.
By the way: The iterative growing of arrays is a bad programming practice. Care for a proper pre-allocation is real programs:
a = zeros(1, length(m));
...
for t = 1:length(m)
...
sump = 0;
for k = 0:n
...
end
a(t) = sump;
end