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

1 回表示 (過去 30 日間)
Emma Harris 2020 年 8 月 24 日
コメント済み: Emma Harris 2020 年 8 月 25 日
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

サインインしてコメントする。

採用された回答

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 件のコメントなしを表示なしを非表示
Emma Harris 2020 年 8 月 25 日
Ah I see. Many thanks for your response!

サインインしてコメントする。

その他の回答 (1 件)

Vladimir Sovkov 2020 年 8 月 24 日
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 件のコメントなしを表示なしを非表示
Emma Harris 2020 年 8 月 25 日
Thank you for your response! This makes sense.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by