error while using Operands

1 view (last 30 days)
Tarek Eid
Tarek Eid on 29 Mar 2020
Edited: the cyclist on 29 Mar 2020
Hi all
im trying to get this code to run but whenever i do i keep getting this error
if BSgrid(K)~=0 || BSgrid(K+1)~=0 || BSgrid(K+2)~=0 && direction==1
K=BSgrid(K)==0 && K+1==BSgrid(K+1)==0 && K+2==BSgrid(K+2)==0
elseif BSgrid(K)~=0 || BSgrid(K+10)~=0 || BSgrid(K+20)~=0 && direction==2
K=BSgrid(K)==0 && K+10==BSgrid(K+10)==0 && K+20==BSgrid(K+20)==0
end
operands to the || and && operators must be convertible to logical scalar values.
Error in battleshipfinal (line 143)
if BSgrid(K)~=0 || BSgrid(K+1)~=0 || BSgrid(K+2)~=0 && direction==1
what does it mean? and how do i get rid of it

Answers (1)

the cyclist
the cyclist on 29 Mar 2020
Edited: the cyclist on 29 Mar 2020
Here's what is means:
true && true; % This works, and gives a scalar result
[true true] && [true false]; % This gives the error you see
The && and || operators are "short-circuit logical operators". They can be used only on scalar values -- not vectors -- because they have to be able to evaluate to simply a single true or false value, not a vector of values.
If you want a vector of logical values, you should use
[true true] & [true false]; % This works, and gives a vector result

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!