hamad khan
hamad khan

Reputation: 369

How to convert specially formatted data from a text file to a matrix in MATLAB

My file is like below trial.txt

ReducedSize:    True         
Ref_Signal: Force        

1        0,0000000000e+000  -3,14703e-003    0,00000e+000
2            1,0000000000e+000   2,27451e-001    4,66456e-002
123      6,3990000000e+003   3,76442e+001   -6,59653e+000
643          6,4000000000e+003   3,76920e+001   -6,61744e+000
Tagin:           
Ovead:      False    
AveNumber: []        1,00000e+001

I want to remove all the lines starting with text or having nothing on them and then put all the rest of the numeric data into a matrix of 4 columns what I did is as follows.

 fid = fopen('trial.txt', 'r') ;               % Open source file.
 fgetl(fid) ;                                  % Read/discard line.
 fgetl(fid) ;                                  % Read/discard line.
 buffer = fread(fid, Inf) ;                    % Read rest of the file.
 fclose(fid)                                   % first two lines DELETED

 fid = fopen('myFile_truncated.txt', 'w')  ;   % Open destination file.
 fwrite(fid, buffer) ;                         % Save to file.
 fclose(fid) ;

 Data = fileread('myFile_truncated.txt');
 Data = strrep(Data, ',', '.');
 FID = fopen('myFile_truncated1.txt', 'w');
 fwrite(FID, Data, 'char');
 fclose(FID);                                   % changed comma to points for data manipulation

dlmread('myFile_truncated1.txt')                % convert the data to MARTRIX

It works fine however, the text in last 3 lines doesn't let it happen. Can anyone suggest how to delete the first number of line and the last number of line? Also how to delete the lines containing no text, so that graph plotting would be easy?

I do think there is a smarter way to do the things.

Upvotes: 1

Views: 394

Answers (1)

heriantolim
heriantolim

Reputation: 457

Here is what I would do

s = fileread('trial.txt'); % read file into string
s = regexprep(s,',','\.'); % replace any comma with period
s = regexprep(s,' +',' '); % replace any group of spaces with a single space 
M = textscan(s,'%f %f %f %f',4,'HeaderLines',3); % read the numbers
M = [M{:}]; % concatenate all cell elements into a matrix

Upvotes: 1

Related Questions