How to turn this for loop into a matrix?
4 次查看(过去 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 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 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!