MATLAB: *** Write a function called triangle_wave that computes the sum (−1) sin(2 +1) (2 +1) 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 v

image analysistriangle_wave

this is my code and I need your help I couldn't figure out where I'm making mistake.
function theSum = triangle_wave(n)
t = linspace(0, 4*pi, 1001);
for tIndex = 1 : length(t)
this_t = t(tIndex);
k = 1 : n;
numerator = ((-1)^k).*sin(this_t * (2*k+1));
denominator = (2 * k + 1)^2;
theSum(tIndex) = sum(numerator ./ denominator);
end

Best Answer

denominator = (2 * k + 1) .^ 2;
Use the elemtnwise .^ instead of the matrix operation ^ . The same for "(-1)^k" .
The corresponding error message is clear:
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
[EDITED] The formula contains: "Sum from k=0 to n", you code contains:
k = 1:n;
Replace this by k = 0:n. It will be more efficient to move the definition before the loop and pre-allocate the output:
function S = triangle_wave(n)
t = linspace(0, 4*pi, 1001);
S = zeros(size(t)); % Pre-allocation
k = 0:n; % Not 1:n
for tIndex = 1 : length(t)
numerator = ((-1) .^ k) .* sin(t(tIndex) .* (2 * k + 1));
denominator = (2 .* k + 1) .^ 2;
S(tIndex) = sum(numerator ./ denominator);
end