出于好奇,如果我在MATLAB中键入这些代码:
a = logical([12 0 1.2]);
b = boolean([12 0 1.2]);
输出变量a
和b
是相同的(相同的值和类型)。那么,布尔值(boolean
)和逻辑值(logical
)之间有什么区别吗?
快速查看布尔函数可以为您的问题提供一个很好的答案:
如果在Matlab控制台中输入:edit boolean
,您将得到:
function y = boolean(x)
%BOOLEAN Creates a boolean vector.
% This function is typically used in Simulink parameter dialogs, such as
% the Constant block dialog. This function generates a logical vector,
% which is treated as a boolean value in Simulink. Now that logical is a
% MATLAB type, this function is essentially just an alias.
%
% Y = BOOLEAN(X) Converts the vector X into a boolean vector.
%
% Example:
% boolean([0 1 1]) returns [0 1 1]
%
% See also LOGICAL.
% Copyright 1990-2012 The MathWorks, Inc.
narginchk(1,1);
if ~isreal(x)
DAStudio.error('Simulink:utility:BooleanCannotBeComplex');
end
y = logical(x);
如果您看一下这个函数的最后一行,就可以看到布尔函数调用逻辑函数。
这个函数本质上只是一个别名
了。 - Danlogical
是MATLAB内置函数,boolean
是Simulink函数。
在输入 help boolean
后,部分返回内容如下:
此函数通常用于Simulink参数对话框,例如常量块对话框。此函数生成一个逻辑向量,在Simulink中被视为布尔值。现在,由于逻辑是MATLAB类型,因此该函数实际上只是一个别名。
如果您在命令行上输入 edit boolean
,您会发现它基本上只是调用输入的 logical
函数。
明确一点:在MATLAB中(至少现在)不存在boolean
数据类型。
以下是OP所述的示例:
>> a = logical([12 0 1.2]); >> b = boolean([12 0 1.2]); >> whos a b Name Size Bytes Class Attributes
a 1x3 3 logical b 1x3 3 logical
boolean
不是一个被认可的类型:
>> cast(a,'boolean')
Error using cast
Unsupported class for conversion.
正如其他答案所说,boolean
函数是由Simulink提供的,仅仅是对logical
转换的一个别名。
Boolean现在只是逻辑的别名,因为逻辑也是MATLAB类型。在Simulink中仍然使用Boolean。事实上,Boolean本身只是简单地调用函数logical。
boolean
在 Matlab 中真的存在吗?您使用的是哪个版本的 Matlab? - Luis Mendoboolean
与Simulink有些关联。顺便说一下,谢谢你的回复。这个问题并不是很重要,但我只是好奇 :) - tashuhka