Search code examples
regexmatlabmathsparse-matrix

Matlab: how to work with sparse keys to access sparse data?


I am trying to access the sparse mlf with the keys such as BEpos and BEneg where one key per line. Now the problem is that most commands are not meant to deal with too large input: bin2dec requires clean binary numbers without spaces but the regexp hack fails to too many rows -- and so on.

How to work with sparse keys to access sparse data?

Example

K>>  mlf=sparse([],[],[],2^31,1);  
BEpos=Cg(pos,:)

BEpos =

   (1,1)        1
   (2,3)        1
   (2,4)        1

K>> mlf(bin2dec(num2str(BEpos)))=1
Error using bin2dec (line 36)
Binary string must be 52 bits or less.

K>> num2str(BEpos)

ans =

1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
0  0  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

K>> bin2dec(num2str('1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0'))
Error using bin2dec (line 36)
Binary string must be 52 bits or less.

K>> regexprep(num2str(BEpos),'[^\w'']','')
Error using regexprep
The 'STRING' input must be a one-dimensional array
of char or cell arrays of strings.

Manually works

K>> mlf(bin2dec('1000000000000000000000000000000'))

ans =

   All zero sparse: 1-by-1

Solution

  • Consider a different approach using manual binary to decimal conversions:

    pows = pow2(size(BEpos,2)-1 : -1 : 0);
    inds = uint32(BEpos*pows.')
    

    I haven't benchmarked this, but it might work faster than bin2dec and cell arrays.

    How it works

    This is pretty simple: the powers of 2 are calculated and stored in pows (assuming the MSB is in the leftmost position). Then they are multiplied by the bits in the matching positions and summed to produce the corresponding decimal values.