# Issue with 'for' loop - trying to iterate through and change certain values to 0 in array

1 visualización (últimos 30 días)
Emma Harris el 24 de Ag. de 2020
Comentada: Emma Harris el 25 de Ag. de 2020
I have a 22x1 array (class double) containing the results of earlier calculations named x_results. I wish to iterate through this array and change values that are equal to 0.3095 to 0. I am currently using the following for loop:
for i = 1:length(x_results)
z = x_results;
if z(i) == 0.3095
z(i) = 0;
else
z(i) = x_results(i);
end
end
What I am trying to say: Check the data in x_results. If a value is equal to 0.3095, change it to 0. If a value does not equal 0.3095, leave it alone. What do I need to change in the above code to implement this effect? It has no impact on x_results in its current form and the values of 0.3095 remain.
Many thanks
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

KSSV el 24 de Ag. de 2020
Editada: KSSV el 24 de Ag. de 2020
Loop is not required. Get the logical indices and do it. Let A be your array.
tol = 10^-5 ;
val = 0.3095 ;
idx = abs(A-val)<=tol ; % get the indices
A(idx) = 0 ;
You cannot comapre floatting point values using == 0. You need to set a tolerance and get the indices as shown above.
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Emma Harris el 25 de Ag. de 2020
Ah I see. Many thanks for your response!

Iniciar sesión para comentar.

### Más respuestas (1)

Vladimir Sovkov el 24 de Ag. de 2020
If the equality must be exact, just
x_results(x_results==.3095)=0;
and nothing else (sometimes can produce an incorrect result due to rounding of the machinery binary arithmetic, it depends...). If some dispersion of the values around 0.3095 is expected and permitted with some tolerance t, do
t=1e-10; % tolerance
x_results( abs(x_results-.3095)<=t )=0;
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Emma Harris el 25 de Ag. de 2020
Thank you for your response! This makes sense.

Iniciar sesión para comentar.

### Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

R2018a

### Community Treasure Hunt

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

Start Hunting!

Translated by