Reference to values in another table
1 view (last 30 days)
Show older comments
Hello,
my problem is about referencing / finding values from T2.Value in T1.A. If there is no exact value in T1.A I need the nearest value. If there are two values in T1.A with the same difference to T2.Value MatLab should use the smaller one.
T2.Output should be the value of T1.B in the same row as value T1.A:
T2.Value = [304.1471; 275.2672; 285.0389]
T2.Output = [16.0200; 0.1600; 2.0400]
Thank you!
0 Comments
Answers (1)
Vinai Datta Thatiparthi
on 17 Jul 2019
Hi!
From the description, it appears to me that you have two tables t1, t2, with the columns A,B and value, output respectively. You compare the values of t2.value with the values in t1.A, and whichever difference is least, the corresponding t1.B value is stored in t2.output. The tiebreaker cases would be the lesser of the two values, and even further, the value with the lesser index.
I have assumed some random values for these 3 columns to illustrate the working with an example. The problem can be addressed with a simple and straightforward code as follows –
% Define the input columns (My random values)
A = [5 7 10]';
B = [5000 7000 10000]';
value = [6 8 9]';
output = zeros(3,1);
% Create the tables
t1 = table(A,B);
t2 = table(value,output);
% Algorithm starts here
for i=1:numel(t2.value)
diffVec = abs(t2.value(i) - t1.A);
least = min(diffVec);
indices = find(diffVec == least);
val = min(A(indices));
out = find(t1.A == val);
t2.output(i) = t1.B(out(1)); % out(1) is to counter the tiebreaker case,
% when t1.A has recurring values but with different corresponding t1.B values
end
0 Comments
See Also
Categories
Find more on Numeric Types in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!