Optimization of a simple IF-FOR loop
1 view (last 30 days)
Show older comments
How can I optimize the following code so that it runs faster?
for i=1:iNZ;
iPointsinSlice=1;
for j=1:iNCUr;
if UrContourZ(j)==ZSlice(i);
iPointsinSlice = iPointsinSlice+1;
UrPointX(iPointsinSlice-1)=1 + (UrContourX(j)-Offset(1,1));
UrPointY(iPointsinSlice-1)=1 + (UrContourY(j)-Offset(2,1));
end
end
end
0 Comments
Answers (1)
random09983492
on 18 Jun 2013
Hi Mohsen,
A few things I will recommend:
1. Take advantage of Matlab's Profiler. Type profview in the Command Window to access it. From here you can run code and see what lines are taking the most time to run, etc. Profiler can also give you hints on how to optimize your code.
2. I don't know what your full code looks like, but in this code snippet you presented, you do not initialize the arrays URPointX or URPointY. Prior to the for loop, you should initialize them like this:
URPointX = zeros(maxRowsX, maxColumnsX);
URPointY = zeros(maxRowxY, maxColumnsY);
This way, the arrays are allocated in memory and do not have to be reallocated every loop iteration since they don't change size.
3. Here are two links for general code performance improvement for Matlab. Vectorization is very important.
If you want more specific help, please post a full code that runs.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!