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

4 次查看(过去 30 天)
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.

采纳的回答

Monica Roberts
Monica Roberts 2022-5-17
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 个评论
Jeremy Salerno
Jeremy Salerno 2022-5-23
编辑:Jeremy Salerno 2022-5-23
I can't believe that the answer was so simple, thank you so much. The speed was greatly improved just by adding the semicolons

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by