Question on why tilde cannot return the opposite statement result

3 ビュー (過去 30 日間)
Jing Gao
Jing Gao 2020 年 2 月 12 日
コメント済み: Stephen23 2020 年 2 月 12 日
Hi there, I want to compute the mean of working hours for those aged 30-50, here're code I wrote:
Q4_ans_test = mean( adultdata.hours_per_week( adultdata.age>30 & adultdata.age<=50))
Q4_ans_test2 = mean( adultdata.hours_per_week(adultdata.age>30 & ~adultdata.age>50),'omitnan')
The problem is the second statement returns "NaN". As I understand ,~ means the opposite of your following statement, and I expect to get the same answer as that in the first line of code. Anyone has idea on what's happening? Thank you so much!

採用された回答

James Tursa
James Tursa 2020 年 2 月 12 日
Precedence of ~ is hgher than >, so it gets performed first. You need to use parentheses:
~(adultdata.age>50)
  2 件のコメント
Jing Gao
Jing Gao 2020 年 2 月 12 日
It works. Thank you a lot for your help and explanation!

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 2 月 12 日
~ binds more tightly than > does, so ~adultdata.age>50 is the same as (~adultdata.age)>50

dpb
dpb 2020 年 2 月 12 日
Q4_ans_test2 = mean( adultdata.hours_per_week(adultdata.age>30 & ~(adultdata.age>50)));
Without the parentheses, the ~operator applies only to the variable adultdata.age and logical not applied to numeric converts anything nonzero to 1 so presuming nobody in the dataset is of age zero, the second includes all elements. There would still needs be a NaN in the mix somewhere, though, to return NaN as the result, but that's the reason why result is different; it is different set of data.
  3 件のコメント
Walter Roberson
Walter Roberson 2020 年 2 月 12 日
For numeric values, ~X is (X == 0) . The exception is that ~nan is an error, whereas (nan == 0) is false
Walter Roberson
Walter Roberson 2020 年 2 月 12 日
There would still needs be a NaN in the mix somewhere, though
No, with the ~ turning out false and the & condition being there, the logical condition was turning out false, so no elements were selected from the data, so mean() was being applied to an empty matrix. mean() of empty is NaN rather than empty.

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by