MATLAB中的逻辑与数值数组

Elp*_*rto 6 arrays performance matlab

我正在比较两个二进制数组.我有一个数组,其中值可以是1或0,如果值相同则为1,如果不相等则为0.请注意我正在做除检查之外的其他事情,因此我们不需要进入矢量化或代码的性质.

什么更有效,在MATLAB中使用数值数组或逻辑数组?

gno*_*ice 5

逻辑值比大多数数值占用更少的字节,如果您处理非常大的数组,这是一个加号.您还可以使用逻辑数组进行逻辑索引.例如:

>> valArray = 1:5;                   %# Array of values
>> numIndex = [0 1 1 0 1];           %# Numeric array of ones and zeroes
>> binIndex = logical([0 1 1 0 1]);  %# Logical array of ones and zeroes
>> whos
  Name          Size            Bytes  Class      Attributes

  binIndex      1x5                 5  logical       %# 1/8 the number of bytes
  numIndex      1x5                40  double        %#   as a double array
  valArray      1x5                40  double               

>> b = valArray(binIndex)            %# Logical indexing

b =

     2     3     5

>> b = valArray(find(numIndex))      %# You have to use the FIND function to
                                     %#   find the indices of the non-zero
b =                                  %#   values in numIndex

     2     3     5
Run Code Online (Sandbox Code Playgroud)

一个注意事项:如果你要处理零和一些非常稀疏的数组(即很少的数组),最好使用一个数字索引数组,例如你从FIND函数得到的数据.参考下面的例子:

>> binIndex = false(1,10000);      %# A 1-by-10000 logical array
>> binIndex([2 100 1003]) = true;  %# Set 3 values to true
>> numIndex = find(binIndex)       %# Find the indices of the non-zero values

numIndex =

           2         100        1003

>> whos
  Name          Size               Bytes  Class      Attributes

  binIndex      1x10000            10000  logical       %# 10000 bytes versus
  numIndex      1x3                   24  double        %#   many fewer bytes
                                                        %#   for a shorter array
Run Code Online (Sandbox Code Playgroud)