Logical or not logical?

10 次查看(过去 30 天)
Mr M.
Mr M. 2015-3-31
编辑: Adam Wyatt 2015-3-31
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 !?

回答(1 个)

Adam Wyatt
Adam Wyatt 2015-3-31
编辑:Adam Wyatt 2015-3-31
  • 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:
class(1)	% answer = double
class(true)	% answer = logical
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])	% 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)	% answer = double
class(v>3)	% answer = logical
class(v.*(v>3))	% answer = double
class(sum(v>3))	% answer = double
logical(5), class(logical(5))	% answer = 1, logical
logical(-5), class(logical(-5))	% answer = 1, logical
logical(0), class(logical(0))	% answer = 0, logical
logical(.1), class(logical(.1))	% answer = 1, logical
Basically logical(~=0)=true and logical(==0)=false, double(true)=1, double(false)=0 but double(1)~=logical(true)!

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by