0

I am trying to read a csv file use textscan. The fields are seperated with ',' . I used the following code, but it only read in one line of data into the matrix W.

I also tried dlmread(), it got the number of fields wrong.

The file is contructed under linux, matlab is under linux.

file_id = fopen('H:\data\overlapmatrices\cos.mat.10');
W = textscan(file_id, '%f', 'delimiter', ',' , 'EndOfLine', '\r\n');
fclose(file_id);
clear file_id;
gstar2002
  • 495
  • 9
  • 20
  • Hi Guys, thanks for the answers. I check the results and find that textscan() reads all the fields, but put them all in a cell{1,1} which itself is a {1, 10* numberOfFields}. So textscan() do not recognise lines. – gstar2002 Feb 24 '14 at 13:49
  • dlmread() or csvread() which use dlmread() internally, also read all fields but seperate the line at the wrong place. – gstar2002 Feb 24 '14 at 13:50
  • The 1-by-1 cell array is expected as you only specified one pattern to match: `'%f'`. Are there 10 numbers per line? If you want them split into separate cells then you need to specify the pattern to match: `'%f%f%f%f%f%f%f%f%f%f'` (yes, it's a bit awkward; no, `'EndOfLine'` can't be used instead). I'm not sure if this is really an end-of-line issue, but you can also try not including that parameter. – horchler Feb 24 '14 at 20:00
  • Hi horchler, thank you for your reply. But there are still some points that are not clear to me. 1. If 'EndOfLine' is not a delimiter of 'row', then what is the purpose of it? 2. So textscan() will read the whole file, split it into fields use 'delimiter', then use the pattern to mach the fields, one by one. Is it right? – gstar2002 Feb 25 '14 at 09:07

2 Answers2

1

The problem could be in how the end of line is represented in the file (see also this article on Wikipedia). While \r\n (the combination of a carriage return and a newline character) is common on Windows, \n (just the newline character) is the standard on Linux and other Unix systems.

But as ben is saying, csvread might be an easier way how to read the file.

John Manak
  • 13,328
  • 29
  • 78
  • 119
1

you might wanna try csvread, it should do the trick.

or you could alway do something dirty like

fid = fopen( filename );
tline = fgetl(fid);
while ischar(tline) %or some other check
    %sscanf(tline...
    tline = fgetl(fid);    
end
ben
  • 1,380
  • 9
  • 14