这是一个脚本,您可以根据需要调整它的功能:
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
andid_max
是行(即使是空的);
- 确保其中至少有一个不为空;
- 虽然它们不需要排序,但它们的值必须是唯一的(在 ID 内和跨 ID)。
后期编辑:
新版本的代码,基于对定义的新解释:
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()
会解决这个问题(尽管检查数组的前 2 个元素是否具有相同值的函数调用过多)