2010-06-28 46 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 

,但受益的將是更大的,如果你正在做更多的邏輯運算,而不是僅僅循環!