how to find the closest value in in an array for a set of values

2 ビュー (過去 30 日間)
Ross Johnston
Ross Johnston 2017 年 3 月 1 日
コメント済み: Ross Johnston 2017 年 3 月 1 日
Hi there
I have used the following commented code which has given me an array of 2x100 double for QTcProb.
Then I have picked 5 values at random in COQTcsample.
%%take 300 random samples from controlall
[randomcontrol, idxrandomcontrol] = datasample (Controlall(1,:), 300, 'replace', false);
missIndex = true(1, size(Controlall, 2)); %%get the position of the values of the unsampled data
missValue = Controlall(1, :);
missValue(idxrandomcontrol) = []; %%get the values of the unsmapled data
close;
[Prob, QTc] = ksdensity(randomcontrol) %%create ksdensity of the 300 samples
QTcProb= vertcat(QTc,Prob); %%create an 2x100 double with probabilty corresponding to the QTc values
%%take 5 samples from the unsampled data
COQTcsample1 = datasample (missValue, 5, 'Replace', false);
%%compare the 5 sampled values against the QTc values in QTcProb to obtain
%%the probability for each of the samples.
...
I now want to perform an operation to take the 5 values in COQTcsample1 and match them to the closest values of QTc in QTcProb so that I can see what the corresponding probability in QTcProb for each of the 5 values is. (I hope this makes sense?)
Many Thanks
Ross

採用された回答

Adam
Adam 2017 年 3 月 1 日
編集済み: Adam 2017 年 3 月 1 日
e.g., using just inputs:
QTcProb = rand(2,100);
COQTcsample1 = [0.2, 0.3, 0.5, 0.7, 0.9];
diffs = QTcProb(1,:) - COQTcsample1';
[d, idx] = min( abs( diffs ), [], 2 );
probs = QTcProb(2,idx);
Note: If you are using an older version of Matlab you will have to use:
diffs = bsxfun( @minus, QTcProb(1,:), COQTcsample1' );
instead of
diffs = QTcProb(1,:) - COQTcsample1';
The bsxfun notation will work in all versions of Matlab.
  1 件のコメント
Ross Johnston
Ross Johnston 2017 年 3 月 1 日
Thanks Adam this worked perfectly using the bsxfun notation!

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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by