フィルターのクリア

Matrix power vs for loop

7 ビュー (過去 30 日間)
L
L 2023 年 6 月 26 日
回答済み: James Tursa 2023 年 6 月 26 日
Hi.
I have to iterate a linear system of the type x(k+1) = Ax(k), with x being a vector of 1024 elements. I only care about the last vector obtained, this is, x(endtime).
What would be faster?
x0 =rand(1024,1)
x = x0;
for i = 1:endtime
x = A*x
end
or
x = (A^endtime) * x0
Thanks.

採用された回答

Angelo Yeo
Angelo Yeo 2023 年 6 月 26 日
Hi Luisa,
If you only want to calculate the time it took to run a snippet of code, you can use tic and toc. Below is an example. You can see the latter one is faster.
endtime = 10000;
A = rand(1024, 1024);
case1 = tic;
x0 =rand(1024,1);
x = x0;
for i = 1:endtime
x = A*x;
end
toc(case1)
Elapsed time is 1.614399 seconds.
case2 = tic;
x = (A^endtime) * x0;
toc(case2)
Elapsed time is 0.245417 seconds.

その他の回答 (1 件)

James Tursa
James Tursa 2023 年 6 月 26 日
Note that the A^endtime method is probably going to be more accurate as endtime gets larger. The loop method can have a tendancy to build up errors.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by