Clear Filters
Clear Filters

logical indexing possible to increase speed?

8 views (last 30 days)
In this loop I convert a 26 Hz accelerometer signal to a 5 seconds interval array. The objective is to find the number of acc values for each 5 second interval. The reason for doing this is that the sample frequency is not exaclty 26, and sometimes there is some missing data in the acc signal. The code works, but takes up a lot of time when processing larger files. My feeling/hope is that creating this new vector can be faster using logical indexing. I just can't figure out how.... Any suggestions?
A = accTimeVector; % Timestamps of acc signal in seconds
length = fix(A(length(A))/5);
acc_5s_interval = zeros(1,length); % create vector with 5 sec intervals
j=0;
for i = 1:length(acc_5s_interval)
acc_5s_interval(i) = numel(A(A>= j & A < j+5));
j=j+5;
end

Accepted Answer

George Abrahams
George Abrahams on 31 Dec 2022
Edited: George Abrahams on 31 Dec 2022
% Dummy timestamps for 32 second, 26 Hz signal starting at 31416 seconds.
signalDuration = 32;
hz = 26;
startTime = 31416;
A = (0:1/hz:signalDuration) + startTime;
n = length( A );
% Add dummy noise to timestamps.
rng( 1, "twister" )
noise = rand(1,n) * 1/(hz*2);
A = A + [ noise(1:end-1) min(0,noise(end)) ];
% Randomly remove 10% of readings.
keepIdx = randperm( n, floor(n*0.9) );
A = A( sort(keepIdx) );
% Remove all readings during the 2nd second.
A( A>=A(1)+1 & A<=A(1)+2 ) = [];
% Time intervals start from the first timestamp (rather than 0).
% Adding Inf to the edges means that we also count any fractional
% intervals at the end of the data, e.g. the last 0.5s in 10.5s of data
% measured every 1s.
measurementInterval = 5;
edges = seconds( [ A(1):measurementInterval:A(end) Inf] );
histcounts( seconds(A), edges )
ans = 1×7
93 117 112 113 122 124 45
I measured computation time for a 1 hour, 30 Hz, noiseless signal, measured at a time interval of 1 second. On my laptop, your for loop method took 123 milliseconds and the histcounts method took 0.5 milliseconds.
EDIT: Updated example to match question's 5 second interval. Added speed comparsion.

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!