Reading text file using fscanf in octave / matlab into cell array

Rick T picture Rick T · Mar 27, 2013 · Viewed 11.6k times · Source

I have a comma delimited single text file with strings and integers that I'm trying to import into a cell array. I then want to export it to several files based on the same Resonance Freq. and add text to the filename row

This is a sample of the text file to import: (please note the file will be much larger then this)

Resonance Freq,number,Filename,time,fs,Split-3675,Session Num
277.912902832031250,1,p000001,00:00:01,44100,3675,0
123.912902832031250,2,p000002,00:00:02,44100,3675,2
277.912902832031250,3,p000003,00:00:03,44100,3675,0
277.912902832031250,4,p000001,00:00:01,44100,3675,1
343.912902832031250,5,p000002,00:00:02,44100,3675,0
277.912902832031250,6,p000003,00:00:03,44100,3675,4

And this is the exported text files I want created (text file1)

277.912902832031250,1,/tmp/p000001.wav,00:00:01,44100,3675,0
277.912902832031250,3,/tmp/p000003.wav,00:00:03,44100,3675,0
277.912902832031250,4,/tmp/p000001.wav,00:00:01,44100,3675,1

And this is the exported text files I want created (text file2)

123.912902832031250,2,/tmp/p000002.wav,00:00:02,44100,3675,2

And this is the exported text files I want created (text file3)

343.912902832031250,5,/tmp/p000002.wavadded ,00:00:02,44100,3675,0

I'm having a problem with fscanf and using comma delimited data

fid = fopen('/tmp/freq_range_color_coded.txt');
m_s = fscanf(fid,'%f %f %s %s %f %f %f');
fclose(fid);

when I access a cell like m_s(1,2) I get back a single letter instead of a field. How can I get it so when I type m_s(1,2) I get back the whole field example

m_s(2,1) should give me 277.912902832031250

thanks

PS I'm using octave and textscan is not compatible with it.

Answer

DMR picture DMR · Mar 27, 2013

Try skipping the header line when importing with textscan:

fid = fopen('/tmp/freq_range_color_coded.txt');
m_s = textscan(fid,'%f %f %s %s %f %f %f','delimiter', ',', 'HeaderLines', 1);
fclose(fid);