BeYo
BeYo

Reputation: 31

octave/matlab read text file line by line and save only numbers into matrix

I have a question regarding octave or matlab data post processing. I have files exported from fluent like below:

                     "Surface Integral Report"

       Mass-Weighted Average
          Static Temperature                  (k)

          crossplane-x-0.001            1242.9402
          crossplane-x-0.025            1243.0017
          crossplane-x-0.050            1243.2036
          crossplane-x-0.075            1243.5321
          crossplane-x-0.100            1243.9176

And I want to use octave/matlab for post processing. If I read first line by line, and save only the lines with "crossplane-x-" into a new file, or directly save the data in those lines into a matrix. Since I have many similar files, I can make plots by just calling their titles. But I go trouble on identify lines which contain the char "crossplane-x-". I am trying to do things like this:

clear, clean, clc;
% open a file and read line by line
fid = fopen ("h20H22_alongHGpath_temp.dat");
% save full lines into a new file if only chars inside
txtread = fgetl (fid)
num_of_lines = fskipl(fid, Inf);
char = 'crossplane-x-'
for i=1:num_of_lines,
  if char in fgetl(fid)
    [x, nx] = fscanf(fid);
    print x
  endif
endfor
fclose (fid);

Would anybody shed some light on this issue ? Am I using the right function ? Thank you.

Upvotes: 2

Views: 8542

Answers (1)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22215

Here's a quick way for your specific file:

>> S = fileread("myfile.dat");       % collect file contents into string
>> C = strsplit(S, "crossplane-x-"); % first cell is the header, rest is data
>> M = str2num (strcat (C{2:end}))  % concatenate datastrings, convert to numbers
M =

   1.0000e-03   1.2429e+03
   2.5000e-02   1.2430e+03
   5.0000e-02   1.2432e+03
   7.5000e-02   1.2435e+03
   1.0000e-01   1.2439e+03

Upvotes: 1

Related Questions