Improving speed of nested loops
1 view (last 30 days)
Show older comments
Hi, I have a potentially seemingly simple question; I'd like to know how I could go about improving my coding abilities. I have 4D (x,y,z,t) array of data, that I go through and run calculations on each point on the 3D map. So far, what I do is something like this:
Mn = zeros([192,64,64]);
[Other, Variables] = deal(mx);
hWaitBar = waitbar(0,'Mapping...')
for i = 1:192
for j = 1:64
for k = 1:64
% ...Some calculations, e.g.
tSeries = 4D_DataSet(i,j,k,:);
tSeries = permute(tSeries,[3 4 1 2]);
Mn(i,j,k) = mean(Series(1,:));
%...And More calculations...
end
end
waitbar(i/192)
end
delete(hWaitBar)
is there a way to parse through i,j,k (or x,y, and z) that would be much faster, or more efficient. Again, This works, but just would like to inquire on brighter and more experienced minds than my own to help me learn to be better. Thank you in advance for any and all insight.
Edwin
3 Comments
Cedric
on 5 Aug 2015
Edited: Cedric
on 5 Aug 2015
I just have 5 minutes now, but there are means to perform computations in ND along given dimensions, to fit surfaces, etc. The best is to train using a simple example. Assume that we are working on a 3D grid 3x2x2 and we have 4 points in time:
data = randi( 10, 3, 2, 2, 4 ) ;
Now it is easy to perform the means that you are doing in one operation per time boundary:
mx = mean( data(:,:,:,1:2), 4 ) ;
mn = mean( data(:,:,:,end-1:end), 4 ) ; % Here I don't know what you need to do,
% because your code and comment don't match.
I don't give numbers because RANDI will generate different numbers each time, but this setup is small enough so you can display data, mx, etc, and check with your numbers that it works (or that i made a little mistake that is easy to correct ;-)).
And then it is the same for differences:
mgDiff = mn - mx ;
I don't know what your function polyfitData does, and it depends on which toolbox you have on your system, but then you should be able to use maybe REGRESS, or tools from the Curve Fitting Toolbox, or tools from the Optimization Toolbox (e.g. LSQCURVEFIT) for the rest.
The trick is to train on small setups or in lower dimension. If you need an array of first differences D along the 3rd dimension of a 3D array X, for example, your reflex may be to build a triple loop that goes from 1 to size(X,)-1 along the 3rd dimension and computes D(i,j,k)=X(i,j,k+1)-X(i,j,k). But then you e.g. google "MATLAB difference", find the DIFF function, read a bit and end up trying:
>> X = randi( 10, 2, 2, 3 )
X(:,:,1) =
6 7
10 6
X(:,:,2) =
9 10
9 1
X(:,:,3) =
9 10
7 6
>> D = diff( X, 1, 3 )
D(:,:,1) =
3 3
-1 -5
D(:,:,2) =
0 0
-2 5
and seeing that it works with no loop.
Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!