Reading line by line from a text file using fgetl

4 views (last 30 days)
Hi,
I have a text file which has some comment lines and data lines - frequency(f), magnitude(m) in dB and angle(a) as shown below.
File description:For every frequency value, there are 16 dB values and 16 angle values and f goes from f1 to fn where n is 3000.The data is in a notepad file and parts of one line of data extend to the next line even after using the unwrap option in notepad, as shown below.
Problem: When I tried to read this file line by line using fgetl, m20 to a32 for frequency f1 or any frequency is considered as a separate line. Is there a way to read from f1 to a32 as a single line? The final required data format should be 'n' rows, each row having 33 columns.
Please advise. Any suggestion is appreciated.
File Format:
Comment 1
Comment 2
Header
f1 m1 a1 m2 a2 ...m19 a19
m20 a20 ....... m31 a31 m32 a32
f2 |m1 a1 m2 a2 ...m19 a19
m20 a20 ....... m31 a31 m32 a32
.
.
fn m1 a1 m2 a2 ...m19 a19
m20 a20 ....... m31 a31 m32 a32

Answers (1)

Walter Roberson
Walter Roberson on 24 May 2012
If the fields are all floating point numbers, then:
Headers = 4; %if that is a blank line after Comment 2
numfields = 1 + 2 * 16; %or is it 1 + 2 * 32 ? You write 16 but you number up to 32
thisfmt = repmat('%f', 1, numfields);
fid = fopen(YourFileName, 'rt');
datacell = textscan(fid, thisfmt, 'HeaderLines', Headers, 'CollectOutput', 1);
fclose(fid);
yourdata = datacell{1};
  1 Comment
Shaleen
Shaleen on 24 May 2012
Thank you very much, your post helped me solve my problem. I apologize for getting my numbering wrong, it should have been 'm16' and 'a16' as the last two columns. So I guess, with 'fgetl' command, this wouldn't have worked.
With your textscan command as it is, the data was still being saved on the next row for one particular frequency and the remaining columns were filled with NaNs. I tried including one more optional parameter in the textscan command like :
datacell = textscan(fid, thisfmt, 'HeaderLines', Headers, 'CollectOutput', 1, 'Delimiter', '\n');
and this put all the 33 columns in one row.
Thank you for pointing me in the right direction.I appreciate your help.

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!