How can I increase the speed and efficiency of this for loop?
Show older comments
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.
Accepted Answer
More Answers (0)
Categories
Find more on Creating and Concatenating Matrices 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!