Location of a value in a matrix

17 visualizaciones (últimos 30 días)
Ismita
Ismita el 6 de Dic. de 2022
Comentada: Ismita el 7 de Dic. de 2022
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

Respuestas (2)

Walter Roberson
Walter Roberson el 6 de Dic. de 2022
x = 0:0.5:20
x = 1×41
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000 8.0000 8.5000 9.0000 9.5000 10.0000 10.5000 11.0000 11.5000 12.0000 12.5000 13.0000 13.5000 14.0000 14.5000
find(x == 9.5)
ans = 20
However...
x = 0:0.1:20
x = 1×201
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000 2.6000 2.7000 2.8000 2.9000
find(x == 0.3)
ans = 1×0 empty double row vector
[found, idx] = ismembertol(0.3, x)
found = logical
1
idx = 4
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)
maxy = 0.9996
idx_oneway = 17
idx_anotherway = find(y == maxy)
idx_anotherway = 17
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 comentarios
Walter Roberson
Walter Roberson el 6 de Dic. de 2022
x2 = 0:0.5:20;
find(x2 == 9.5)
ans = 20
In any case, please re-read my response where I say "Don't DO that" -- and I show what to do instead.
Ismita
Ismita el 7 de Dic. de 2022
Thank you so much

Iniciar sesión para comentar.


David Hill
David Hill el 6 de Dic. de 2022
x=0:.5:20;
f=find(x==9.5)
f = 20
x(f)
ans = 9.5000
  1 comentario
Ismita
Ismita el 6 de Dic. de 2022
Thank you . But I see the exact location -
"x2 = 0:0.5:20;
find(x2 == 9.5)
ans =
1×0 empty double row vector"
Could you please suggest?

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by