finding the closest grid

2 ビュー (過去 30 日間)
Matt Learner
Matt Learner 2012 年 2 月 16 日
編集済み: Daniel 2013 年 10 月 15 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by