How to simplify this piece of code?
显示 更早的评论
I am working on implementing the PAC2002 Magic Formula on MATLAB, and while I was writing the code for computing all the matrices of the model, I noticed the computing time required was getting way too big. I know this is happening because of so many variables I'm using in order to compute these matrices, but I don't know how to make it simpler really. Let me show an example:
Thetax = zeros(length(sigmax),length(Bx),length(Ex));
for i = 1:1:length(sigmax)
for j = 1:1:length(Bx)
for k = 1:1:length(Ex)
Thetax(i,j,k) = Cx*atan(Bx(j,k)*sigmax(i,j)-Ex(i,j)*(Bx(j,k)*sigmax(i,j)-atan(Bx(j,k)*sigmax(i,j))));
end
end
end
where length(sigmax) = 201, length(Bx) = 10, length(Ex) = 10.
I should mention that sigmax, Bx and Ex are not just vectors, they are 2 dim matrices. But this didn't affect much the computing time. It was the last equation that really did. This equation in particular increased so much the computing time, from just a few seconds to a few minutes. Everyt time I had to compute a matrix, it would be depending on 2 variables, and so I'd use some code like this:
Svx= zeros(length(Fz),length(dfZ)):
for i = 1:1:length(Fz)
for j = 1:1:length(dfZ)
Svx(i,j) = Fz(i)*(PVX1+PVX2*dfZ(j))*LVX*LMUX;
end
end
The problem is that almost every independent variable in these equations is depending on other 2, making themselves 2nd dim matrices, and so I have lots of pieces of code in my script that look like the last equation. By the time I added the 1st equation, the computing time just went to the moon! Is there any way around this problem, that does not require calling so many fors?
Thank you.
1 个评论
Adam
2015-3-25
If you have 2d matrices I would not recommend using e.g.
length( sigmax )
You should use the size operator with an explicit dimension to avoid unwanted surprises in some cases.
采纳的回答
更多回答(1 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Just for fun 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!