Deleting duplicate records in a vector when records are complex and rounding errors cause problems

I want to remove duplicate entries from a vector on Matlab. The problem I am facing is that rounding errors stop the Matlab built-in "unique" function. Ideally, I would like to establish some kind of tolerance for a “unique” function or a small procedure that would otherwise remove duplicates. If both the real and imaginary parts of the two records differ by less than 0.0001, then I am glad to consider them equal. How can i do this?

Any help would be greatly appreciated. Thanks

+3
source share
3 answers

, :

X = ... (input vector)
[b, i] = unique(round(X / (tolerance * (1 + i))));
output = X(i);

(, , b ~ Matlab).

, , , , -. , , :

X = ... (input vector)
[b, ind] = unique(round(X / (tolerance * (1 + i))));
X = X(ind);
[b, ind] = unique(round(X / (tolerance * (1 + i)) + 0.5 * (1 + i)));
X = X(ind);

, , , unique. - - , . .

, , for:

X = sort(X);
last = X(1);
indices = ones(numel(X), 1);
for j=2:numel(X)
  if X(j) > last + tolerance * (1 + i)
    last = X(j) + tolerance * (1 + i) / 2;
  else
    indices(j) = 0;
  end
end
X = X(logical(indices));

, , ( - , , . , ).

+4

, , 1-8, . 1e-8 .

% unique function that assumes 1e-8 is equal
function [out, I] = unique(input, first_last)

threshold = 1e-8;
if nargin < 2
    first_last = 'last';
end
[out, I] = sort(input);
db = diff(out);
k = find(abs(db) < threshold);
if strcmpi(first_last, 'last')
    k2 = min(I(k), I(k+1));
elseif strcmpi(first_last, 'first')
    k2 = max(I(k), I(k+1));
else
    error('unknown flag option for unique, must be first or last');
end
k3 = true(1, length(input));
k3(k2) = false;
out = out(k3(I));
I = I(k3(I));
end
0

. X, , , , , real_tol imag_tol. , .

function X_unique = unique_complex_with_tolerance(X,real_tol,imag_tol)
     X_sorted = sort(X); %Sorts by magnitude first, then imaginary part.

     dX_sorted = diff(X_sorted);
     dX_sorted_real = real(dX_sorted);
     dX_sorted_imag = imag(dX_sorted);

     remove_idx = (abs(dX_sorted_real)<real_tol) & (abs(dX_sorted_imag)<imag_tol);

     X_unique = X_sorted;
     X_unique(remove_idx) = [];
return

Please note that this code will remove all elements that satisfy this difference tolerance. For example, if X = [1 + i, 2 + 2i, 3 + 3i, 4 + 4i], real_tol = 1.1, imag_tol = 1.1, then this function will return only one element, X_unique = [4 + 4i], even though you you can consider, for example, X_unique = [1 + i, 4 + 4i] as a valid answer.

0
source

All Articles