Construct Power of Matrix without for loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Azzi Abdelmalek
le 11 Août 2013
Modifié(e) : Azzi Abdelmalek
le 11 Août 2013
Example
A=magic(2);
N=3;
B=cell2mat(arrayfun(@(x) A^x,1:N,'un',0))
0 commentaires
Plus de réponses (2)
Jan
le 12 Août 2013
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 commentaires
Ming
le 11 Août 2013
Modifié(e) : Ming
le 11 Août 2013
1 commentaire
Walter Roberson
le 11 Août 2013
Note: arrayfun() just hides the "for" loop. If you are willing to use it, then Azzi's example does what you ask.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!