Haider
Haider

Reputation: 341

Reading a text file into MatLab as a Matrix with arbitrary delimiters

I have a text file of the form:

[  1.80000000e+02   1.00000000e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   6.00000000e+00]
[  1.80000000e+02   1.00035019e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   3.00000000e+00]
.
.
. 

[  1.80000000e+02   1.00035019e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   3.00000000e+00]

I would like to load this data into MatLab as a Matrix, where the numbers in each list of the text file are the contents of a single row. So, in effect, each row in the Matrix will contain one whole list. I tried doing various things but nothing is getting me the right result. I think it is due to the weird formatting, where each new line has white space at the beginning + also after every new '['. Any help would be appreciated?

Upvotes: 1

Views: 62

Answers (1)

I don't know of a super elegant solution. I would bang out something with sscanf like this:

f = fopen('mytmp.txt') ;
s = textscan(f,'%s','Delimiter','[ ]','MultipleDelimsAsOne',true) ;
fclose(f) ;
m = numel(s{1}) ;
v = NaN(m,1) ;
for ii = 1:m
    v(ii) = sscanf(s{1}{ii},'%f') ;
end
m = reshape(v,13,[])' ;

Upvotes: 1

Related Questions