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

4 visualizzazioni (ultimi 30 giorni)
Jeremy Salerno il 17 Mag 2022
Modificato: Jeremy Salerno il 23 Mag 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
end
Thank you for the help. I can try to add some test data, if needed.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Monica Roberts il 17 Mag 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);
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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Jeremy Salerno il 23 Mag 2022
Modificato: Jeremy Salerno il 23 Mag 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

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by