我写了一种算法,可以找到信号中的局部最大值和最小值。
[id_max, id_min] = find_max_min(signal);
我现在要检查:最大值和最小值的交替是否受到尊重
i.e. id_max(1)<id_min(1)<id_max(2)<id_min(2)<...
we could start with a minimum..this is not known
假设:
id_max = [1 3 5 7 10 14 20];
id_min = [2 4 6 8 16 19];
我想有2个向量missing_max
missing_min
指示丢失的最大值和最小值的位置。
当两个连续的最小值(最大值)之间没有最大值(最小值)时,就会缺少最大值id_min (id_max)
(最小值)。
在此示例中,在id_max的第7个位置缺少最大值,因为在id_min中有两个连续的值(16 19)之间没有最大值。
那我们有
missing_max = [7]
missing_min = [5]
自从
id_max = [1 3 5 7 10 14 X 20];
id_min = [2 4 6 8 X 16 19];
(用XI标记缺少的值)
如果交替正确,则向量应为空。您能建议一种无需for循环的有效方法吗?
提前致谢
如果需要,这是一个可以适应功能的脚本:
id_max = [1 3 5 7 10 14 20];
id_min = [2 4 6 8 16 19];
% Group all values, codify extremity (1-max, 0-min), and position
id_all = [ id_max, id_min ];
code_all = [ones(size(id_max)), zeros(size(id_min))];
posn_all = [ 1:numel(id_max), 1:numel(id_min) ];
% Reshuffle the codes and positions according to sorted IDs of min/max
[~, ix] = sort(id_all);
code_all = code_all(ix);
posn_all = posn_all(ix);
% Find adjacent IDs that have the same code, i.e. code diff = 0
code_diff = (diff(code_all)==0);
% Get the indices of same-code neighbors, and their original positions
ix_missing_min = find([code_diff,false] & (code_all==1));
ix_missing_max = find([code_diff,false] & (code_all==0));
missing_min = posn_all(ix_missing_min+1);
missing_max = posn_all(ix_missing_max+1);
关于ID的警告:
id_min
和id_max
是行(即使为空);以后编辑:
基于有关定义的新解释的新版本代码:
id_max = [1 3 5 7 10 14 20];
id_min = [2 4 6 8 16 19];
%id_max = [12 14]
%id_min = [2 4 6 8 10];
id_min_ext = [-Inf, id_min];
id_max_ext = [-Inf, id_max];
% Group all values, and codify their extremity (1-max, 0-min), and position
id_all = [ id_max_ext, id_min_ext ];
code_all = [ones(size(id_max_ext)), zeros(size(id_min_ext))];
posn_all = [ 0:numel(id_max), 0:numel(id_min) ];
% Reshuffle the codes and position according to sorted positions of min/max
[~, ix] = sort(id_all);
code_all = code_all(ix);
posn_all = posn_all(ix);
% Find adjacent IDs that have the same code, i.e. code diff = 0
code_diff = (diff(code_all)==0);
% Get the indices of same-code neighbours, and their original positions
ix_missing_min = find([code_diff,false] & (code_all==1));
ix_missing_max = find([code_diff,false] & (code_all==0));
missing_min = unique(posn_all(ix_missing_min-1))+1;
missing_max = unique(posn_all(ix_missing_max-1))+1;
但是,该代码包含一个细微的错误。该错误将由提出问题的人员删除,或者由他/她以确实清楚所要内容的方式改进了问题之后由我删除。:-)由于我们有2个虚拟极值(ID = −∞时,一个最大值和一个最小值),因此第一个缺失的极值将被标记两次:一次在-∞处,一次在ID的第一个元素处列表。unique()
会解决这个问题(尽管过多的函数调用要检查数组的前两个元素是否具有相同的值)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句