Construct Power of Matrix without for loop
이전 댓글 표시
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
채택된 답변
추가 답변 (2개)
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
2013년 8월 12일
+1
Azzi Abdelmalek
2013년 8월 12일
Good idea to avoid repeating power operation.
댓글 수: 1
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.
카테고리
도움말 센터 및 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!