フィルターのクリア

Construct Power of Matrix without for loop

1 回表示 (過去 30 日間)
Ming
Ming 2013 年 8 月 11 日
Hi, everyone:
Suppose I have a 2 by 2 matrix A, if I want construct a larger matrix B that is defined as:
B=[A, A^2, A^3, A^4, ... A^N];
is it possible to do it without for loop?
Thanks

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 8 月 11 日
編集済み: Azzi Abdelmalek 2013 年 8 月 11 日
Example
A=magic(2);
N=3;
B=cell2mat(arrayfun(@(x) A^x,1:N,'un',0))

その他の回答 (2 件)

Jan
Jan 2013 年 8 月 12 日
Azzi's suggestion is fine for N=3. If you are talking about larger N, neither the repeated power operator nor arrayfun nor cell2mat are efficient:
N = 10000
A = rand(2, 2);
tic;
B = cell2mat(arrayfun(@(x) A^x,1:N,'un',0));
toc
tic;
B = zeros(2, 2, N);
P = 1;
for k = 1:N
P=P*A;
B(:,:,k) = P;
end
B = reshape(B, 2, N * 2);
toc
Elapsed time is 0.199776 seconds.
Elapsed time is 0.039983 seconds.
So I'd prefer the more efficient FOR loop.
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2013 年 8 月 12 日
+1
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 8 月 12 日
Good idea to avoid repeating power operation.

サインインしてコメントする。


Ming
Ming 2013 年 8 月 11 日
編集済み: Ming 2013 年 8 月 11 日
Thanks very much!
Do you know if A is a 2 by 2 by N matrix, can I use "arrayfun" or any other way to do:
B=[A(:,:,1), A(:,:,1)*A(:,:,2), A(:,:,1)*A(:,:,2)*A(:,:,3), ... , A(:,:,1)*A(:,:,2)*A(:,:,3)* ... *A(:,:,N)]
without for loop?
  1 件のコメント
Walter Roberson
Walter Roberson 2013 年 8 月 11 日
Note: arrayfun() just hides the "for" loop. If you are willing to use it, then Azzi's example does what you ask.

サインインしてコメントする。

カテゴリ

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