How can I increase the speed and efficiency of this for loop?

4 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Monica Roberts
Monica Roberts am 17 Mai 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.
  1 Kommentar
Jeremy Salerno
Jeremy Salerno am 23 Mai 2022
Bearbeitet: Jeremy Salerno am 23 Mai 2022
I can't believe that the answer was so simple, thank you so much. The speed was greatly improved just by adding the semicolons

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by