Boolean and numeric array in MATLAB

I am comparing two binary arrays. I have an array where the values โ€‹โ€‹can be either equal to or equal to zero if the values โ€‹โ€‹are the same and equal to zero if they are not. Please note that I do things other than validation, so we donโ€™t need to embed code in the vector or nature.

Which is more efficient using a numerical array or logical array in MATLAB?

+6
performance arrays matlab
source share
2 answers

Boolean values take up less bytes than most numbers , which is a plus if you are dealing with very large arrays. You can also use logical arrays for logical indexing . For example:

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

Note: If you are dealing with arrays of zeros and very scarce (i.e. very few), it is best to use an array of numerical indices, for example, enter the FIND function. Take the following example:

 >> 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 
+5
source share

Logically, of course! Matlab has the ability to compress 8 elements into 1 byte. (Regardless of whether he does it or not, another thing).

 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 

result

 4.561173 seconds 3.454697 seconds 

but the advantage will be much greater if you do more logical operations, and not just a loop!

+1
source share

All Articles