# Logical or not logical?

12 views (last 30 days)
Mr M. on 31 Mar 2015
Edited: Adam Wyatt on 31 Mar 2015
v = [1,2,3,4,5,6]
v > 4 gives back: 0 0 0 0 1 1
after this I wonder that
v(v > 4) is valid, but v([0,0,0,0,1,1]) is not a valid expression!
Maybe the problem is that 1 is true, not one, therefore the following has to be used:
v(logical([0,0,0,0,1,1]))
OK
but how it is possible that sum(v > 4) is valid and equal to 2?
if 1 is true, than true + true = true !?

Adam Wyatt on 31 Mar 2015
Edited: Adam Wyatt on 31 Mar 2015
• All numbers are by default of class type "double" (unless specifically cast as int etc.).
• Logical values are of class "logical".
• Matlab displays 0 (false) and 1 (true) for logical values, but they are not equal to 0 or 1.
• Casting true or false to a number results in a value of 0 or 1
• This is standard convention, casting a logical (or boolean or bool) to a numeric data type results in either 0 or 1 (false or true) and casting a numeric data type as a logical (or boolean or bool) results in false for zero and true for anything else.
Check:
When you write
v([0 0 0 0 1 1])
what you are actually saying is [v(0) v(0) v(0) v(0) v(1) v(1)], i.e. you are entering the index locations. For example
v([1 1 1 2 2 1 1 1 2 1 1])&#09;% answer = [1 1 1 2 2 1 1 1 2 1 1];
is perfectly valid!!
You can perform arithmetic with logical values and logic with numeric values, but Matlab automatically casts it as the appropriate class.
Check
class(true + true)&#09;% answer = double