Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse text file in MATLAB [duplicate]

How can I parse file in MATLAB? The data in the text has this format:

p
15.01245  20.478
12.589  58.256
n
16.589  87.268
52.367  46.256
2.589  58.02

I want to store each data in separate array (i.e; store data under letter p in array 1, and data under letter n in array 2).

any help?

like image 487
userInThisWorld Avatar asked Aug 02 '26 23:08

userInThisWorld


2 Answers

Here is another solution:

fstring = fileread('test.txt'); % read the file as one string
fblocks = regexp(fstring,'[A-Za-z]','split'); % uses any single character as a separator
fblocks(1) = []; % removes anything before the first character
out = cell(size(fblocks));
for k = 1:numel(fblocks)
    out{k} = textscan(fblocks{k},'%f %f','delimiter',' ','MultipleDelimsAsOne', 1);
    out{k} = horzcat(out{k}{:});
end
like image 130
yuk Avatar answered Aug 05 '26 13:08

yuk


You can do this by using fgets to read in the file line by line and checking for lines containing p and n.

fid = fopen('pn.txt'); % open the file
i2 = 1;
data = {};
while ~feof(fid) % loop over the following until the end of the file is reached.
      line = fgets(fid); % read in one line
      if strfind(line,'p') % if that line contains 'p', set the first index to 1
          i1 = 1;
      elseif strfind(line,'n') % if that line contains 'n' set the first index to 2
          i1 = 2;
      else
          data{i1,i2} =  str2num(line); % otherwise, it the line contains numbers, add them to a cell array.
          i2 = i2 + 1;
      end
end
fclose(fid);

%convert the cell array into two matrices.
p = cell2mat(data(1,:));
p = reshape(p,[numel(p)/2,2])
n = cell2mat(data(2,:));
n = reshape(n,[numel(n)/2,2])
like image 25
Molly Avatar answered Aug 05 '26 15:08

Molly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!