How to turn this for loop into a matrix?

4 ビュー (過去 30 日間)
Alex
Alex 2014 年 3 月 22 日
コメント済み: Jan 2014 年 3 月 22 日
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 件のコメント
Alex
Alex 2014 年 3 月 22 日
I added more details to the code. Hope it is more clear now. Thank you for your time.
Jan
Jan 2014 年 3 月 22 日
" b=[1x9 array]'" is not useful. Better post in valid Matlab syntax.

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

採用された回答

Star Strider
Star Strider 2014 年 3 月 22 日
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.

その他の回答 (0 件)

カテゴリ

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