how can I store values generated from a nested loop into an arrray ?
Show older comments
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
More Answers (2)
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
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!