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

3 vues (au cours des 30 derniers jours)
Ross Johnston
Ross Johnston le 1 Mar 2017
Commenté : Ross Johnston le 1 Mar 2017
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

Réponse acceptée

Adam
Adam le 1 Mar 2017
Modifié(e) : Adam le 1 Mar 2017
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 commentaire
Ross Johnston
Ross Johnston le 1 Mar 2017
Thanks Adam this worked perfectly using the bsxfun notation!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by