How to use intersect command with a tolerance value?

44 ビュー (過去 30 日間)
Vishal Dwivedi
Vishal Dwivedi 2019 年 2 月 12 日
コメント済み: Jan 2019 年 2 月 15 日
I have two vector with different lenght and I want to compare the values of the vectors one by one with a certain tolerance because the numbers are similar but not equal, e.g. 222.456 and 222.389. I was using the command intersect but it only gives me the numbers that are exactly the same.
  1 件のコメント
madhan ravi
madhan ravi 2019 年 2 月 12 日
perhaps ismembertol() ?

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2019 年 2 月 12 日
編集済み: Jan 2019 年 2 月 15 日
While ismembertol might be useful, I'm still puzzled by the way it defines the tolerance.
If the vectors are not too large (some thousand elements should be fine), a simple loop approach should be sufficient:
function [AI, BI] = CommonElemTol(A, B, Tol)
A = A(:);
B = B(:);
nA = numel(A);
M = zeros(1, nA);
% Collect the index of the first occurrence in B for every A:
for iA = 1:nA
dist = abs(A(iA) - B); % EDITED: Of course abs() is needed
Ind = find(dist < Tol, 1); % Absolute tolerance
% Ind = find(dist ./ A(iA) < Tol, 1); % Relative tolerance
if ~isempty(Ind)
M(iA) = Ind;
end
end
AI = find(M); % If any occurrence was found, this A exists
if isempty(AI) % prevent: Empty matrix: 0-by-1
AI = [];
end
BI = M(AI); % at this index in B
end
  3 件のコメント
Stephen23
Stephen23 2019 年 2 月 15 日
I suspect that
dist = (A(iA) - B);
should be
dist = abs(A(iA) - B);
otherwise there is no absolute involved.
Jan
Jan 2019 年 2 月 15 日
@Stephen: Of course. Thanks.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by