how can I store values generated from a nested loop into an arrray ?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Omar Maklad
el 28 de Ag. de 2016
Comentada: Omar Maklad
el 31 de Ag. de 2016
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 ?
0 comentarios
Respuesta aceptada
Andrei Bobrov
el 28 de Ag. de 2016
Editada: Andrei Bobrov
el 28 de Ag. de 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
Más respuestas (2)
dpb
el 28 de Ag. de 2016
Editada: dpb
el 28 de Ag. de 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.
0 comentarios
Thorsten
el 29 de Ag. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!