如果我有:
a = [5000 8000 20000 22000 30000]';
是否有任何快速方法可以检测给定数字是否在另一个数字范围内(例如5000),然后将两者都删除并用中点替换它们?理想情况下,我想将此附加到IF语句,但我真的不知道可以使用什么样的函数或数学方法来执行此操作。
所需的输出将是a
:
= [6500 21000 30000];
答案 0 :(得分:3)
accumarray
的方法可能最适合解决它 -
th = 5000 %// threshold to choose next elements (edit to specific input)
a = sort(a(:)) %// sort elements
matches = diff(a)>th
idx = cumsum([0 ; matches])+1 %// index each element with their group IDs
out = (accumarray(idx,a,[],@min) + accumarray(idx,a,[],@max))./2
%// outputs are the midpoints of the min-max boundaries within each group
答案 1 :(得分:2)
试试这个:
a = [5000 8000 20000 22000 30000]'; %'// example data
th = 5000; %// example threshold
[ii, jj] = find(triu(abs(bsxfun(@minus, a, a.'))<=th, 1)); %'// find pairs of close points
a(ii) = (a(ii)+a(jj))/2; %// replace the first of each pair by the average
a(jj) = []; %// remove the second of each pair
答案 2 :(得分:1)
以更简单,更有效的方式,您可以使用4行代码。
b = diff(a);
inds = find(abs(b) <= 5000);
a(inds) = (a(inds) + a(inds+1))/2;
a(inds+1) = [];
试试吧。没有排序,没有bxsfun,没有棘手的事情。稍微更改它也可以作为一个函数完成,只需用阈值变量替换5000
并对矩阵的维度做一些裁决(主要是diff
的原因),你很高兴。