how can I store values generated from a nested loop into an arrray ?

1 view (last 30 days)
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 ?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 28 Aug 2016
Edited: Andrei Bobrov on 28 Aug 2016
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

More Answers (2)

dpb
dpb on 28 Aug 2016
Edited: dpb on 28 Aug 2016
Create independent index variables and increment them each pass thru the loop...
"The Matlab way" would be to use the vectorization features in Matlab syntax (see the "dot" operators .* and .^ and friends...)
BTW, if you have Signal Processing Toolbox there are a couple of waveform generation functions there; specifically sawtooth does symmetric triangle-wave form. Unless, of course, the "feature" of the rounded form of the lower number of series in the approximation is an intended result.

Thorsten
Thorsten on 29 Aug 2016
The general scheme is to do define a vector of values
t = linspace(tmin, tmax, Nvalues);
and run a loop
for i=1:numel(t)
res(i) = your formula depending on t(i)
end
Of course it is often mor efficient to use vectorisation, as shown in Andrei's answer.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!