How to select values of array using the logical operator "OR"?

1 回表示 (過去 30 日間)
Emerson De Souza
Emerson De Souza 2012 年 9 月 13 日
GOAL: Hi, I have an array A and want to build a new array B by selecting two or more values using the logical operator OR.
MY SOLUTION: I wrote the following lines:
A=[1 3 4 3 7 8 5 4 6 5]';
B= zeros(size(A));
for i = 1:numel(A)
if A(i) == 3 || 5;
B(i) = A(i);
else
B(i) = NaN;
end
end
PROBLEM: The logical operator OR is not working. The array B is not correct because it is identical to array A. As a result I expected to see:
NaN
3
NaN
3
NaN
NaN
5
NaN
NaN
5
However, If I remove the logical operator OR, B is correct but does not include the value 5.
I wonder if someone could tell me what I'm doing wrong and how to correct these lines.
Thank you in advance for your attention
Emerson
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 9 月 14 日
B = nan(size(A));
i1 = any(abs(bsxfun(@minus,A(:),[3,5])) < eps(100),2);
B(i1) = A(i1);

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

採用された回答

Image Analyst
Image Analyst 2012 年 9 月 13 日
編集済み: Image Analyst 2012 年 9 月 13 日
Try
if A(i) == 3 || A(i) == 5 % BTW, no trailing semicolon needed.
Or, better yet, try this vectorized way:
A = [1 3 4 3 7 8 5 4 6 5]'
indexesToReplace = A == 3 | A == 5
B = nan(size(A));
B(indexesToReplace) = A(indexesToReplace)
  2 件のコメント
Emerson De Souza
Emerson De Souza 2012 年 9 月 14 日
Thank you Image Analyst, both suggestions worked well.
Wish you a nice evening
Emerson
Image Analyst
Image Analyst 2012 年 9 月 14 日
If your numbers are floating point, not integers, then you'd best use Andrei's code. Refer to the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by