Why is the or statement making something true?

1 vue (au cours des 30 derniers jours)
Eli Tsao
Eli Tsao le 16 Oct 2019
Modifié(e) : the cyclist le 16 Oct 2019
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?

Réponses (3)

the cyclist
the cyclist le 16 Oct 2019
Modifié(e) : the cyclist le 16 Oct 2019
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 le 16 Oct 2019
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 le 16 Oct 2019
"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...

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by