How to turn this for loop into a matrix?

4 vues (au cours des 30 derniers jours)
Alex
Alex le 22 Mar 2014
Commenté : Jan le 22 Mar 2014
My code spends a significant amount of time in for loop. Could you, please, help to convert this for loop to a matrix operation? Please, notice that each output is an input for the next step.
b=[1x9 array]';
y=[1x9 array]';
expmA = zeros(100,9,9 );
Ainvbm = zeros(100, 9);
for m=1:100;
Ma = [ 1x9 array ]; contains m-dependent variable
Mb = [ 1x9 array ]; contains m-dependent variable
Mc = [ 1x9 array ]; contains m-dependent variable
Md = [ 1x9 array ]; contains m-dependent variable
Me = [ 1x9 array ]; contains m-dependent variable
Mf = [ 1x9 array ]; contains m-dependent variable
Mg = [ 1x9 array ]; contains m-dependent variable
Mh = [ 1x9 array ]; contains m-dependent variable
Mj = [ 1x9 array ]; contains m-dependent variable
A = [Ma; Mb; Mc; Md; Me; Mf; Mg; Mh; Mj];
expmA(m,:,:)= expm(A*time(m));
Ainvbm(m,:) = A\b;
end
% This loop is bottleneck of my code. How to convert it to a matrix operation?
for m=1:100;
y = squeeze(expmA(m,:,:))*(y+Ainvbm(m,:)')-Ainvbm(m,:)';
end
  3 commentaires
Alex
Alex le 22 Mar 2014
I added more details to the code. Hope it is more clear now. Thank you for your time.
Jan
Jan le 22 Mar 2014
" b=[1x9 array]'" is not useful. Better post in valid Matlab syntax.

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 22 Mar 2014
If [Ma ... Mj] and A don’t change in the loop, define them once before the loop rather than in each iteration of the loop.
This code ran quickly:
time = 0:0.01:0.99;
A = -rand(9,9);
b = rand(1,9)';
y = rand(1,9)';
tic
for m = 1:100
expmA(m,:,:) = expm(A*time(m));
Ainvbm(m,:) = A\b;
end
for m = 1:100
y = squeeze(expmA(m,:,:))*(y+Ainvbm(m,:)')-Ainvbm(m,:)';
end
toc
Elapsed time is 0.046041 seconds.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by