How can I optimize the following code so that it runs faster?
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
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.