Issue with 'for' loop - trying to iterate through and change certain values to 0 in array
1 回表示 (過去 30 日間)
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;
z(i) = x_results(i);
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.
KSSV 2020 年 8 月 24 日
編集済み: KSSV 2020 年 8 月 24 日
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 件)
Vladimir Sovkov 2020 年 8 月 24 日
If the equality must be exact, just
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;