fast evaluation of x(k+1) = x(k)*e(k)
11 ビュー (過去 30 日間)
古いコメントを表示
Is there any special trick how to evaluate fast this recurrent formula:
x(1) = x0
x(k+1) = x(k)*e(k), k= 1,2, ...N-1
where N = length(x) = length(e)+1
e ... known vector
I mean faster then standard for-loop:
x(1) = x0;
for k = 1:N-1
x(k+1) = x(k)*e(k);
end
2 件のコメント
Matt J
2024 年 1 月 8 日
If N is large enough that speed would matter, you are likely running the risk of underflow or overflow of the successive products.
回答 (1 件)
Dyuman Joshi
2024 年 1 月 8 日
編集済み: Dyuman Joshi
2024 年 1 月 8 日
Timings of for loop with preallocation and vectorization are comparable for a large number of elements -
x = 69420;
N = 5e6;
e = rand(1,N);
F1 = @() forloop(x, e, N);
F2 = @() forlooppre(x, e, N);
F3 = @() vectorization(x, e);
fprintf('Time taken by for loop without preallocation for a vector with %g elements = %f seconds', N, timeit(F1))
fprintf('Time taken by for loop with preallocation approach for a vector with %g elements = %f seconds', N, timeit(F2))
fprintf('Time taken by vectorized approach for a vector with %g elements = %f seconds', N, timeit(F3))
y1 = F1();
y2 = F2();
y3 = F3();
%Comparing results using tolerance
all(abs(y1-y2)<1e-10 & abs(y2-y3)<1e-10)
%% Function definitions
%For loop without preallocation
function x = forloop(x, e, N)
for k=1:N
x(k+1) = x(k)*e(k);
end
end
%For loop without preallocation
function x = forlooppre(x, e, N)
%preallocation
x = [x zeros(1, N)];
for k=1:N-1
x(k+1) = x(k)*e(k);
end
end
%Vectorized approach
function x = vectorization(x, e)
x = x.*[1 cumprod(e)];
end
10 件のコメント
Dyuman Joshi
2024 年 1 月 9 日
The code above was ran on
ver
Linux and MATLAB Version R2023b Update 5
参考
カテゴリ
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!