Return Unique Element with a Tolerance

后端 未结 7 1363
无人共我
无人共我 2020-11-27 06:40

In Matlab, there is this unique command that returns thew unique rows in an array. This is a very handy command.

But the problem is that I can\'t assign tolerance to

7条回答
  •  情话喂你
    2020-11-27 06:54

    I've come across this problem before. The trick is to first sort the data and then use the diff function to find the difference between each item. Then compare when that difference is less then your tolerance. This is the code that I use:

    tol = 0.001
    [Y I] = sort(items(:));
    uni_mask = diff([0; Y]) > tol;
    %if you just want the unique items:
    uni_items = Y(uni_mask); %in sorted order
    uni_items = items(I(uni_mask));  % in the original order
    

    This doesn't take care of "drifting" ... so something like 0:0.00001:100 would actually return one unique value.

    If you want something that can handle "drifting" then I would use histc but you need to make some sort of rough guess as to how many items you're willing to have.

    NUM = round(numel(items) / 10); % a rough guess
    bins = linspace(min(items), max(items), NUM);
    counts = histc(items, bins);
    unit_items = bins(counts > 0);
    

    BTW: I wrote this in a text-editor away from matlab so there may be some stupid typos or off by one errors.

    Hope that helps

提交回复
热议问题