hhh
hhh

Reputation: 52840

Matlab: how to read binary numbers from a file?

File has binary numbers separated by newline.

$ cat bin_MCS.txt |tail
000000001100000000000010000000000
000000010010000000000010000000000
000011000000000000000000000000000
000010100000000000000000000000000
000101000000000000000000000000000
000100100000000000000000000000000
000100001000000000000010000000000
000000110000000000000010000000000
000001010000000000000010000000000
000010001000000000000010000000000

Matlab reads the binary numbers in DEC, wrong

>> textread('bin_MCS.txt')

ans =

   1.0e+30 *

    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000
    0.0000

Goal

I need to read the binary numbers to a matrix like this [1 0 1;0 1 1]. The first puzzle is to be able to read the binary numbers. Then the next puzzle is to be able to read them in a certain format.

Upvotes: 2

Views: 1325

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

A slightly convoluted, but personal favorite of mine:

>> (char(textread('bin_MCS.txt','%s'))-'0') * pow2(32:-1:0).'
ans =
    25166848
    37749760
   402653184
   335544320
   671088640
   603979776
   553649152
   100664320
   167773184
   285213696

If you use textscan, it'll even be faster than the bin2dec version:

tic
for ii = 1:1e3

    fid = fopen('bin_MCS.txt', 'r');
        C = textscan(fid,'%s');
    fclose(fid);

    R = (char(C{1})-'0') * pow2(32:-1:0).';

end
toc


tic
for ii = 1:1e3
    bin2dec(textread('bin_MCS.txt','%s'));
end
toc

Results:

Elapsed time is 0.182339 seconds.
Elapsed time is 15.600509 seconds.

Granted, this is not a completely fair test, but at least it illustrates that there is a substantial difference.

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112659

Read as strings an then convert to decimal numbers with bin2dec:

bin2dec(textread('bin_MCS.txt','%s'))

ans =

    25166848
    37749760
   402653184
   335544320
   671088640
   603979776
   553649152
   100664320
   167773184
   285213696

EDIT:

To read the individual binary digits into a matrix, you can use this (48 is the ASCII code for '0'):

cell2mat(textread('bin_MCS.txt','%s'))-48

Upvotes: 4

Related Questions