Efficient way to find closest spacing of a "comb" array
Show older comments
Hello!
I found that the most inefficient part of some code is a nested loop that is not vectorized; I'm not sure how to vectorize it though at the innermost loop.
The problem is to find, in a "comb" array, the maximum number of "teeth" within a given interval. If you don't know what a comb array is, it is mostly zeros with occasional values of 1 (the teeth). This is then convolved with a waveform, but you don't really need to know that part. It is important to know how many teeth are close together.
The comb array is multidimensional, but really only the one dimension is relevant, the one looped over in the innermost loop. The code is:
% Check for number of delays within 8 ms for comb function
delay_interval = 7; % One ms less than 8ms
length_of_comb = length(comb_array);
num_checks = length_of_comb - delay_interval;
%multiWaitbar('Part 2',0);
for n = 1:num_row_delays
%multiWaitbar('Part 2',n/num_row_delays);
for m = 1:num_hole_delays
charge_per_8ms_delay = 0; %start out at zero
for p = 1:num_checks
chunk_to_check = comb_array(n,m,p:p+delay_interval);
ctc = sum(chunk_to_check);
if ctc > charge_per_8ms_delay
charge_per_8ms_delay = ctc;
end
end
chg_per_delay_array(n,m) = charge_per_8ms_delay;
end
end
%multiWaitbar('Part 2','Close');
Any thoughts on how to make this run faster (i.e., smarter!) are welcomed!
Thanks.
Doug Anderson
Accepted Answer
More Answers (1)
Jan
on 8 Jul 2015
As far as I can see, this is a "moving sum" with a threshold.
B = ones(1, delay_interval+1);
...
% Replacement of the "for p" loop:
value = filter(B, 1, squeeze(comb_array(n, m, :)));
chg_per_delay_array(n,m) = value(find(value, 1, 'last'));
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!