Compare every element in a vector and find the minimum distance to a constant value.

33 views (last 30 days)
I was wondering if there is an easy way to find the minimum difference between every entry in a vector and a constant. Its kind of hard to explain but here is an example:
You have a vector [2, 8, 15, 11, 31], and a constant 12. Now I want to find which two elements when substracted from eachother, are closest to this constant. In this example this would be 15-2 = 13, which is the difference that is closest to 12. Thus, in the actual code it should also consider the difference between every entry in this array, not just consecutive entries. You can see that the constant can be larger than the smallest difference in the vector (12>(11-8=2))...
Also, in my problem, it might come up that two entries both have the same distance, and therefore are both closest to 12. If it is possible it would be the nicest if you would get a sorted list with the elements ranked from best to worst.
So far I got as far that I get a list with all differences and their errors to the innerTrackDistance constant, but then I don't know how to find which two elements produced that optimal result...
Here is my current code (I hope you can make out what I tried from the mess ;-P):
clear all; clc; close all
diameters = unique([53, 54, 73, 70, 92, 70.5, 58, 84, 60, 61, 24.5, 63, 119, 67, 91, 74.5, 76.5]);
innerTrackDistance = 10.35;
L = numel(diameters);
differences = zeros(L-1,L);
% calculate the differences:
for i = 2:L
tmp_vct = [diameters(i:end) diameters((L-i+2):end)];
differences(i-1,:) = abs(diameters - tmp_vct);
end
% Put differences into vector form, and clear all zero-entries:
differences = (differences(:))';
differences(differences == 0) = [];
% Compare them to the constant value to find the best fitting one:
for k = 1:length(differences)
error(k) = abs(differences(k) - innerTrackDistance);
end
% determine which entry of error is the smallest one:
smallestError = min(error);
smallestErrorIndex = find(error == min(error));
% How to find these elements in the original diameters vector???
clear i; clear j; clear k;
I hope you understand what I mean. Thanks in advance for any help!

Answers (1)

Ameer Hamza
Ameer Hamza on 25 May 2020
Something like this
x = [2, 8, 15, 11, 2]; % modified so that it have two minumum distances
a = 12;
D = abs(x - x.' - a);
minD = min(D, [], 'all');
idx = find(minD==D);
[first_element, second_element] = ind2sub([numel(x) numel(x)], idx);

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!