how can i make loop run faster?

1 次查看(过去 30 天)
Ekin Ceyda Cetin
Ekin Ceyda Cetin 2017-1-7
编辑: Jan 2017-1-9
I am trying to make a for-loop run faster.
I used matrices for part of my code instead of loops,
but I can't seem to do it for the loop in the last part of the code below.
Because in the .^ part I get the error that says matrix dimension doesn't match.
Any ideas that can help?
% code
sym sigm
pd6=makedist('exponential','mu',1)
rand1=random(pd6,[2000,100000])
X.r=size(data);
d2 = zeros(X.r(1),10^5);
d3 = zeros(X.r(1),10^5);
mc1=linspace(1,X.r(1),X.r(1));
mc2=linspace(1,10^5,10^5);
mc3=linspace(1,1000,1000);
d2(mc1(1:X.r(1)),mc2(1:10^5))=(rand1(mc1(1:X.r(1)),mc2(1:10^5)));
sig1=-1./(0.2+0.0001*mc3(1:1000));
sig2=((0.2+0.0001*mc3(1:1000))-1)./(0.2+0.0001*mc3(1:1000));
dd2 = zeros(1000,10^5);
dd3 = zeros(1000,10^5);
disp(1);
for mc4=1:1000
dd2(mc4,1:10^5)=sum((d2.^sig1(mc4)),1);
dd3(mc4,1:10^5)=sum((d2.^sig2(mc4)),1);
end
  1 个评论
Jan
Jan 2017-1-9
编辑:Jan 2017-1-9
Replace the expensive power operator 10^5 by a cheap constant 1e5.

请先登录,再进行评论。

回答(1 个)

Jordan Ross
Jordan Ross 2017-1-9
Hello Ekin,
As I understand you are trying to eliminate your for-loop so that your code will run faster but are unable to vectorize due to a dimension mismatch. After looking at your code, it seems that sig1 and sig2 are defined as row vectors instead of column vectors. This is causing the dimension mismatch when trying to vectorize. You can take the transpose of sig1 and sig2 as follows:
sig1 = sig1';
sig2 = sig2';

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by