0

I have of bunch of CSV files to read in Matlab. All of files has similar structure, except last field is optional. I.e. some files contain it, others are not.

Also files contain both textual and numeric fields, so csvread is not applicable.

Only alternative I know is textscan. Unfortunately, I can't find specifiers for optional fields.

I am looking at spec:

formatSpec = '%d%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%s%[^\n\r]';

and wish last %s be optional.

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
  • I think you can use [xlsread](http://se.mathworks.com/help/matlab/ref/xlsread.html). The function is meant to be used for excel sheets, but I think it should work. – patrik Apr 07 '15 at 13:10

3 Answers3

0

You could try the strsplit function

http://www.mathworks.com/help/matlab/ref/strsplit.html

Mateo Hrastnik
  • 533
  • 1
  • 7
  • 20
0

To read a file line-by-line, you can use the function fgetl. It reads one line, removes newline-characters and returns the line as a string. At the end of the file, a -1 is returned.

You can then use the sscanf to extract the data according to your format spec (including the %s). If your input data doesn't contain any string at the end, then the last field was empty.

fid = fopen('file.txt','r');
while 1
    line = fgetl(fid);
    if line == -1
        break;
    end
    A = sscanf(line,formatSpec);
    ...
end

You can then do whatever you need with A.

For example look at the following example:

line = '1 2.5 3.6 abc';
A = sscanf(line,'%d %f %f %s')

A =
    1.0000
    2.5000
    3.6000
   97.0000
   98.0000
   99.0000

The string will be A(4:end). The string was empty if isempty(A(4:end)), that way you can store the data as you like, e.g. in a cell.

hbaderts
  • 14,136
  • 4
  • 41
  • 48
0

Assuming you don't need the optional column, why not ignore the rest of the line by %*s and delimiter set to newline?

  • That's not a safe assumption to make, as "optional" doesn't imply "irrelevant". It could very well be vital in cases where it is present. – Bryan Walker Apr 30 '16 at 19:23