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

1 visualización (últimos 30 días)
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

Respuesta aceptada

KSSV
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.

Más respuestas (1)

Vladimir Sovkov
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;

Categorías

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

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by