Minimalist
Minimalist

Reputation: 975

Parsing a Large Text in Sections in Matlab

I have a large text file as below imported in MATLAB:

Run Lat Long Time
1 32 32 34
1 23 22 21
2 23 12 11
2 11 11 11
2 33 11 12

up to 10 runs etc.

So I'm trying to break up each section in the file: section 1, section 2, etc and write it to 10 different text files. File 1 will have data from Run 1. File 2 will have data from Run 2.

Upvotes: 0

Views: 179

Answers (2)

AGS
AGS

Reputation: 14498

If your data is already loaded into matlab and named A, you could do:

>> a = max(A(:,1));
>> AA={};
>> for i = 1:a
     AA{i}=A(find(A(:,1)==i),:)
     name=sprintf('%d.txt',i);
     dlmwrite(name,AA{i},'\t');
   end

The output will be .txt files containing tab-delimited data.

Upvotes: 0

Salain
Salain

Reputation: 752

What you're looking for is Matlab's textread function. I'll give you the pieces you need and frame out the logic, but you'll need to connect the pieces yourself :)

Your read would look something like this

[head1, head2, head3, head4] = textread(file_name,'%s %s %s %s',1);
[run, lat, long, time] = textread(file_name,'%u %u %u %u');

and your write method would use a loop to iterate over the values in

unique(run)

creating a file with

fout = fopen([base_file_name_out num2str(run_number)]);

and writing to it the values contained in

lat_this_run=Lat(run==run_number);

using the method

fprintf(fout,'%u %u %u\n', lat_this_run, long_this_run, time_this_run)

Upvotes: 1

Related Questions