How to turn this for loop into a matrix?

5 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by