Filter löschen
Filter löschen

Restarting loop from beginning based on condition?

1 Ansicht (letzte 30 Tage)
Benjamin Colbert
Benjamin Colbert am 13 Sep. 2022
Beantwortet: Walter Roberson am 13 Sep. 2022
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

Antworten (1)

Walter Roberson
Walter Roberson am 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.

Kategorien

Mehr zu Signal Processing Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by