필터 지우기
필터 지우기

Restarting loop from beginning based on condition?

조회 수: 1 (최근 30일)
Benjamin Colbert
Benjamin Colbert 2022년 9월 13일
답변: Walter Roberson 2022년 9월 13일
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

답변 (1개)

Walter Roberson
Walter Roberson 2022년 9월 13일
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.

카테고리

Help CenterFile Exchange에서 Signal Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by