finding the closest grid

3 次查看(过去 30 天)
I have 2 variables and each of 3 discretization say for example, first variable have values (2,4,6) and second variable have (1,3,5). so out of these I can make a 9 combination which looks something like this: grid = {(2,1), (2,3), (2,5), (4,1), (4,3), (4,5), (6,1), (6,3), (6,5)}
Suppose if I have a combination (2.8, 4.2) and I would like to find the closest value out of my 9 combination for it
How can I do that ?
Thanks

采纳的回答

Walter Roberson
Walter Roberson 2012-2-16
nearestx = interp1([2,4,6], [2,4,6], comb(:,1), 'nearest');
nearesty = interp1([1,3,5], [1,3,5], comb(:,2), 'nearest');
There are other ways as well.
  2 个评论
Matt Learner
Matt Learner 2012-2-17
Please can you let me know what are the other ways. Cos, I have around 64 combinations obtained from 2 variables and I have to select the nearest combination (out of 64) for the given combination
Walter Roberson
Walter Roberson 2012-2-17
The above will handle that situation as well.
var1vals = sort([2, 4, 6, 7, -3, 11, pi^2, sqrt(30)]);
var2vals = sort([1, 3, 5, 9, 1.15, 33, -5, -8]);
nearestx = interp1(var1vals, var1vals, comb(:,1), 'nearest');
nearesty = interp1(var2vals, var2vals, comb(:,2), 'nearest');
An alternative:
var1vals = sort([2, 4, 6, 7, -3, 11, pi^2, sqrt(30)]);
var2vals = sort([1, 3, 5, 9, 1.15, 33, -5, -8]);
[mindiffx, minidxx] = min(bsxfun(@(a,b) abs(a-b), comb(:,1), var1vals), [], 2);
[mindiffy, minidxy] = min(bsxfun(@(a,b) abs(a-b), comb(:,2), var2vals), [], 2);
nearestx = var1vals(minidxx);
nearesty = var2vals(minidxy);
Note that both of these approaches handle all of the combinations at the same time, if the combinations are stored in the matrix "comb" with the first column being the first variable and the second column being the second variable.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by