Location of a value in a matrix
17 views (last 30 days)
Show older comments
Say, I have a matrix x = 0:0.5:20. How can I find the exact location (according to the array) of the value of x==9.5? thanks
0 Comments
Answers (2)
Walter Roberson
on 6 Dec 2022
x = 0:0.5:20
find(x == 9.5)
However...
x = 0:0.1:20
find(x == 0.3)
[found, idx] = ismembertol(0.3, x)
It is typically (much more often than not) an error to use == to search for a value in a floating point array, with the exception of comparing something that has been extracted from the array. For example,
y = sin(x);
[maxy, idx_oneway] = max(y)
idx_anotherway = find(y == maxy)
max() and min() and indexing create bit-for-bit identical copies of values (except for weird nan values) so you can be sure that == will work for them. But you should rarely use == to compare non-integers to a list created with the : operator.
3 Comments
Walter Roberson
on 6 Dec 2022
x2 = 0:0.5:20;
find(x2 == 9.5)
In any case, please re-read my response where I say "Don't DO that" -- and I show what to do instead.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!