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

1 view (last 30 days)
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

Accepted Answer

KSSV
KSSV on 24 Aug 2020
Edited: KSSV on 24 Aug 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.

More Answers (1)

Vladimir Sovkov
Vladimir Sovkov on 24 Aug 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;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!