How can I increase the speed and efficiency of this for loop?
1 view (last 30 days)
Show older comments
Jeremy Salerno
on 17 May 2022
Edited: Jeremy Salerno
on 23 May 2022
New to MATLAB, so still trying to learn how to write code correctly and efficiently.
In the below script, I window the data, compute the covariance matrix, then perform a Singular Value Decomposition, to compute an azimuth from three-component motion data (Vertical, North-South, and East-West).
It works and runs, but it's really slow, and I assume this is due to the for loop going through each data point within each window one by one.
I tried pre-allocating the covariance matrix outside the for loop, but it does not seem to decrease the runtime.
M=[e n z] %matrix of East-West, North-South, and Vertical (Z) data vectors
len=length(z); %length of Z data (also used as length of E and N since same lengths
windowLength=0.01; %seconds
delta=0.0005; %sample spacing in seconds
az=[]; %container for azimuths computed in below for loop
covmat=zeros(3); %preallocating matrix
for ii=1:len %loop through length of vertical Z component (could have used `e` or `n` length too)
if ii==len-(windowLength/delta) %if we get to the last window, stop the loop
break
end
M(ii:(ii+(windowLength/delta)),:) %window the data matrix during each iteration of the loop
covmat=cov(M(ii:(ii+(windowLength/delta)),:)) %compute covariance matrix
[eigvec,eigenval,v]=svd(covmat) %singular value decompositino
az=[az rad2deg(atan2(eigvec(1),eigvec(2)))] %compute azimuth
end
Thank you for the help. I can try to add some test data, if needed.
0 Comments
Accepted Answer
Monica Roberts
on 17 May 2022
I wonder if a lot of time is spent displaying the output in the command window. You could put a semicolon on the ends of the lines to suppress the output. And it looks like you don't need the first line displaying the values of M.
for ii=1:len %loop through length of vertical Z component (could have used `e` or `n` length too)
if ii==len-(windowLength/delta) %if we get to the last window, stop the loop
break
end
covmat=cov(M(ii:(ii+(windowLength/delta)),:));
[eigvec,eigenval,v]=svd(covmat);
az=[az rad2deg(atan2(eigvec(1),eigvec(2)))];
end
I'm guessing "cov" and "svd" may be taking the longest time, but you could try some of the performance measurement tools MATLAB has like "tic toc" or the profiler app.
More Answers (0)
See Also
Categories
Find more on Logical 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!