Restarting loop from beginning based on condition?
2 views (last 30 days)
Show older comments
I have the code below which is supposed to detect high amplitude events and remove the event and the surrounding rows. The issue is that it doesn't work perfectly. I believe what is happening is that it is removing rows, which renumbers the rows downstream and results in events being skipped. E.g., if detector is on row 50 and removes 40-60, then row 61 is now row 41 and if it was a high amplitude evemt it gets skipped. How do I restart the loop from i=1 whenver a row is removed? Code:
%[data, fs] = audioread("noise.wav");
%t1 = linspace(0, (numel(data)-1)/fs, numel(data));
rng(1)
data = randi(10,1000,1);
threshold = 5;
clear_range = 0; %rows/samples
data = clearRange(data, threshold, clear_range);
%t1 = linspace(0, (numel(data)-1)/fs, numel(data));
%plot(t1, data);
plot(data)
function [data] = clearRange(data, threshold, clear_range, compare_column)
% data: matrix of values to clean
% threshold: value to compare values against
% clear_range: number of rows to delete
% compare_column: column to check for value to compare against threshold
if nargin < 4
compare_column = 1;
end
for i = 1:length(data)
if i > length(data)
break
end
if data(i,compare_column) > threshold
data(max(1, i-clear_range):min(length(data), i+clear_range),:) = [];
end
end
end
0 Comments
Answers (1)
Walter Roberson
on 13 Sep 2022
Don't do that ;-)
Instead, loop backwards. Each time you do a deletion, the elements after will "fall down" to occupy the removed objects, sort of like Tetris. When you are looping forward, that is a problem as it would lead to having to re-examine the current location because some unexamined data falls into the current location. But if you loop backwards, then what is left after the current point is data you have already processed, and you do not need to re-examine it.
0 Comments
See Also
Categories
Find more on Audio I/O and Waveform Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!