Why is the or statement making something true?

1 回表示 (過去 30 日間)
Eli Tsao
Eli Tsao 2019 年 10 月 16 日
編集済み: the cyclist 2019 年 10 月 16 日
I currently have this code:
scores=[99,85,67;90,65,69;98,95,97;80,85,89;98,77,87];
Max_quiz_scores = max(scores)
Overall_max_score=max(Max_quiz_scores);
if Overall_max_score==scores(1,3)|scores(2,3)|scores(3,3)|scores(4,3)|scores(5,3)
disp('3rd column has the highest score')
else
disp('3rd column does not have the highest score')
end
However, whenever I run it, I know the max score is 99 in the first column, but it displays that the third column has the highest score. What am I doing wrong? Am I doing something wrong with the | as or?

回答 (3 件)

the cyclist
the cyclist 2019 年 10 月 16 日
編集済み: the cyclist 2019 年 10 月 16 日
You need
Overall_max_score==scores(1,3) | Overall_max_score==scores(2,3) <etc>
You could do this more concisely as
ismember(Overall_max_score,scores(:,3))
or skip defining Overall_max_score altogether with
ismember(max(scores(:)),scores(:,3))
or
max(scores(:))==max(scores(:,3))
Both of these latter methods use the fact that the syntax
scores(:)
is the matrix scores as a single column vector.

HaMo
HaMo 2019 年 10 月 16 日
This is what a conditional OR statement looks like
if a == x || b == x || c == x
Look up the difference between | and ||
You can also shorten it to this:
[~, ind] = max(max(scores))

dpb
dpb 2019 年 10 月 16 日
"Am I doing something wrong with the | as or?"
Yes you are...the above is the same as
if Overall_max_score==(scores(1,3)|scores(2,3)|scores(3,3)|scores(4,3)|scores(5,3))
and
scores(1,3)|scores(2,3)|scores(3,3)|scores(4,3)|scores(5,3)
will always be logical True as long as even one person in the third column did better than a flat zero on any quiz. | returns only the logical or which is either 0 (false) or ~0 (true).
To write as you did would mean doing the test on each and every element as
if Overall_max_score==scores(1,3)| Overall_max_score==scores(2,3)| ...
Overall_max_score==scores(3,3)| Overall_max_score==scores(4,3)| ...
Overall_max_score==scores(5,3)
...
It would be much simpler to use the optional second return for max something like
[Overall_max_score,imax]==max(Max_quiz_scores);
if imax==3
...
You could get the same result as
[Overall_max_score,imax]=max(scores); % return array max, location in array
[rmax,cmax]=ind2sub(size(scores),imax); % convert index to subscripts row, column
if cmax==3
...
altho one doesn't get the column max'es this way for free...

カテゴリ

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