MATLAB: How can I store values generated from a nested loop into an arrray

loops with rational numbersnested loops storagestoring loop's resultes

if I have this code :-
function S = triangle_wave(n)
S = zeros(1,1001); %preallocation
e = [];
for t = 0:((4*pi)/1000):(4*pi)
for k = 0:n
sigma = (((-1)^k)*sin((2*k+1)*t))/((2*k+1))^2;
e(1, *???*) = sigma; *(%what should I put here instead of (???)?)*

end
r = sum(e(:));
S(1, *???*) = r; *(%what should I put here instead of (???)?)*
end
end
I can't depend on the loop's variable because they are kinda of rational numbers, so how should i store ?

Best Answer

function S = triangle_wave(n)
t = linspace(0,4*pi,1001)';
k = 0:n;
S = sum(bsxfun(@times,sin(bsxfun(@times,t,(2*k+1))),(-1).^k./(2*k+1).^2),2);
end
or with for..end loop
function S = triangle_wave(n)
S = zeros(1001,1); %preallocation
t = linspace(0,4*pi,1001);%0:((4*pi)/1000):(4*pi);
k = 0:n;
for jj = 1:1001
S(jj) = sum(((-1).^k).*sin((2*k+1)*t(jj))./(2*k+1).^2);
end
end