Borrar filtros
Borrar filtros

in the below mentioned code, i get an error in finding some elements (not in all) : 0×1 empty double column vector

11 visualizaciones (últimos 30 días)
m=41;
n=51;
dx=0.0500;
dy=0.0500;
for i=1:m
for j=1:n
x(i,1)=(i-1)*dx;
y(j,1)=(j-1)*dy;
end
end
k=find(x==0.3)

Respuesta aceptada

Steven Lord
Steven Lord el 15 de Ag. de 2023
This behavior is a consequence of floating point arithmetic. See this Answers post and the "Avoiding Common Problems with Floating-Point Arithmetic" section of this documentation page for more information.
If you are using the == operator to attempt to locate a floating-point number in an array, instead subtract the number you're trying to find from the numbers in the array and locate those positions where the difference is smaller than some tolerance or use the ismembertol function.
x = 0:0.1:1
x = 1×11
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
It appears that x contains the value 0.3, but it does not contain exactly 0.3.
checkWithExactEquality = x == 0.3
checkWithExactEquality = 1×11 logical array
0 0 0 0 0 0 0 0 0 0 0
It does contain a value that is extremely close to 0.3, however.
tolerance = 1e-15;
checkWithTolerance = abs(x-0.3) < tolerance
checkWithTolerance = 1×11 logical array
0 0 0 1 0 0 0 0 0 0 0
whichValueTolerance = x(checkWithTolerance)
whichValueTolerance = 0.3000
How far away from 0.3 is the value we found using a tolerance?
howDifferent = whichValueTolerance - 0.3
howDifferent = 5.5511e-17
To do the same with ismembertol:
checkWithIsmembertol = ismembertol(x, 0.3, tolerance)
checkWithIsmembertol = 1×11 logical array
0 0 0 1 0 0 0 0 0 0 0
whichValueIsmembertol = x(checkWithIsmembertol)
whichValueIsmembertol = 0.3000
The ismembertol function found the same value that the check with a tolerance did.

Más respuestas (1)

Torsten
Torsten el 15 de Ag. de 2023
Movida: Torsten el 15 de Ag. de 2023
k = find(abs(x-0.3)==min(abs(x-0.3)))
  2 comentarios
Torsten
Torsten el 15 de Ag. de 2023
Editada: Torsten el 15 de Ag. de 2023
Asking for strict equality of expressions is dangerous because of floating point arithmetic. See @Steven Lord 's answer for a more detailed explanation.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by