필터 지우기
필터 지우기

logical indexing possible to increase speed?

조회 수: 8 (최근 30일)
Bertil Veenstra
Bertil Veenstra 2022년 12월 31일
댓글: Bertil Veenstra 2022년 12월 31일
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

채택된 답변

George Abrahams
George Abrahams 2022년 12월 31일
편집: George Abrahams 2022년 12월 31일
% 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.
  댓글 수: 2
Bertil Veenstra
Bertil Veenstra 2022년 12월 31일
Thanks a lot George!
Bertil Veenstra
Bertil Veenstra 2022년 12월 31일
Yes, quite an improvement indeed. Very happy :-)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by