Use of fopen,fscanf and fclose.

3 views (last 30 days)
Massilon Toniolo da Silva
Massilon Toniolo da Silva on 21 May 2017
Commented: Walter Roberson on 22 May 2017
Dear colleagues,
I have been trying to select rows and columns of a data set in text file. The data I have got is displayed as a 90-by-4 matrix. I would need to have a matrix consisting of all rows but only column 2. The way I have tried to carry it out is as follows:
fid = fopen('chf201.txt','r');
data=fscanf(fid,'%g', [4,inf]);
fclose(fid);
result=data(2,:);
result =
0
Attempted to access data(2,:); index out of bounds because numel(data)=1.
Could you please help me in this matter, since I did not get the 90-by-1 matrix as the result? Kind regards, Massilon
  3 Comments
Walter Roberson
Walter Roberson on 21 May 2017
Is there a header line on the file? What does the first two lines look like?
dpb
dpb on 21 May 2017
Besides whatever is wrong in your attempt to read the data (probably something like what Walter has suggested would be a very good guess),
result=data(2,:);
would be the 2nd row, all columns, not the second column.
Try importdata for the easy-peasy way to read a text file with header and see if it can infer the format automagically.

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 21 May 2017
Try this:
data = importdata('chf201.txt');
column2 = data(:, 2);

Massilon Toniolo da Silva
Massilon Toniolo da Silva on 21 May 2017
Dear Stephen Cobeldick,
I am sorry for the delay. Now I am sending the files annotations_nsr001 and annotations_chf201.txt both from Physionet.org (Normal Sinus Rhythm RR Intervals Database). I thank you very much for any help. Kind regards, Massilon
  1 Comment
Walter Roberson
Walter Roberson on 22 May 2017
I recommend using readtable() for those, if you have R2013b or later. Especially if you have R2014b or later, readtable() will take care of creating datetime objects out of the first column.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!