[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Read file containing multiple data types

From: PhilipNienhuis
Subject: Re: Read file containing multiple data types
Date: Sat, 3 Nov 2018 04:58:00 -0500 (CDT)

Saji Kuttan wrote
> Hi,
> I have a text file which is attached. The file has some header lines, that
> have to be skipped. I am trying to read the data in the file with
> different
> choices such as load, importdata, and fscanf. I think only fscanf can be
> used here. Even with fscanf, I have some problems.
> I used fscanf as :
> *for i=1:33[d,c1,c2,t]=fscanf(fid," %d %s %s %f", "C");printf("%d %f\n",
> d,t)x=fgetl(fid);  % to skip remaining part of the lineend*
> This code is not perfect because:
> (1) I have to manually count the number of lines in the text file. I don't
> know to apply automatic EOF.
> (2) There are some missing data, given as "..." at the end. Here the
> numeric field is changed to character. How it can be solved?
> So please tell me how to read this file and save the data into different
> variables.

This looks like the kind of datafiles I often get, textscan should be
perfect for this kind of jobs.

I first tried with:

   C = textscan (fid, "%d / %d: %s", "headerlines", 10)

but apparently the headerlines option didn't work here (could be due to line
endings, or maybe it's a bug).

So including a workaround for that headerlines issue your file can be read
conveniently with:

  fid = fopen (("data.txt", "r");
  ##  Workaround for non-functional "headerlines" option in textscan
  for ii=1:10
    fgetl (fid);

  ## Remember file position when experimenting with textscan options
  pos = ftell (fid);

  ## Actual textscan call including "literals" in the format string
  C = textscan (fid, "%d / %d: %s");
  ## When experimenting with textscan just do 'fseek (fid, pos)' before each

  fclose (fid)

  ## Rework last column (read as text) into doubles and concatenate
textscan's otput
  C = [ C{1} C{2} (cell2mat (cellfun (@str2double, C{3}, "uni", 0))) ];


Sent from:

reply via email to

[Prev in Thread] Current Thread [Next in Thread]