MATLAB中的逻辑数组与数值数组之间的区别

6

我正在比较两个二进制数组。我的一个数组中的值可以是1或0,如果这些值相同,则为1,否则为0。请注意,我在检查之外还有其他操作,因此我们不需要涉及向量化或代码性质。

在MATLAB中,使用数值数组还是逻辑数组更有效?

2个回答

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

注意:如果你需要处理非常稀疏(即很少有1)的零和一数组,最好使用数值索引的数组,就像你从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

1

当然是逻辑!Matlab有将8个项目压缩到1字节的选项。(它是否这样做是另一回事)。

a=ones(1000); b=(a==1);
tic;for(k=1:100)for(i=1:1000);for(j=1:1000);a(i,j)=a(i,j);end;end;end;toc
tic;for(k=1:100)for(i=1:1000);for(j=1:1000);b(i,j)=b(i,j);end;end;end;toc

结果

4.561173 seconds
3.454697 seconds

但如果你进行更多的逻辑操作而不仅仅是循环,好处会更大!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接