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 ?
0 件のコメント
採用された回答
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
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.
0 件のコメント
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!