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

조회 수: 1 (최근 30일)
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 ?

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 8월 28일
편집: Andrei Bobrov 2016년 8월 28일
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

추가 답변 (2개)

dpb
dpb 2016년 8월 28일
편집: dpb 2016년 8월 28일
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 2016년 8월 29일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by