2010-06-28 47 views
6

我正在比较两个二进制数组。我有一个数组,其中值可以是一个或零,一个如果值是相同的,如果他们不是零。请注意,我正在做其他检查之外的东西,所以我们不需要进入矢量化或代码的性质。MATLAB中的逻辑与数值数组

在MATLAB中使用数值数组或逻辑数组更有效吗?

回答

5

Logical值占用的字节数比大多数numeric值少,如果您处理的是非常大的数组,则这是一个加号。你也可以使用逻辑数组来做logical indexing。例如:

>> 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 

一个注意:如果将处理是非常稀疏的(即极少数的人)的0和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

很好的回答! – Elpezmuerto 2010-06-28 16:24:56

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 

,但受益的将是更大的,如果你正在做更多的逻辑运算,而不是仅仅循环!