Thursday, October 22, 2009

Index of an array element closest to an arbitrary value

>> x = 1:100:1000;

The index of the array which is closest to say 130 is given by

>> [v,idx] = min(abs(x-130));

The answer is

v = 29, idx = 2

No comments:

 
pre { margin: 5px 20px; border: 1px dashed #666; padding: 5px; background: #f8f8f8; white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ }