endowdly
endowdly

Reputation: 119

MATLAB - Stitch Together Multiple Files

I am new to MATLAB programming and some of the syntax escapes me. So I need a little help. Plus I need some complex looping ideas.

Here's the breakdown of what I have:

Here's what I need to do:

What is implied:

Well, that's pretty much it. I did a search for 'merging mulitple files' and found this. That isn't exactly what I need to do...I don't need to take part of a file, or data from files, and write it to a new one. I'm simply...concatenating...? This would be simple in Java or Perl, but I only have MATLAB as a tool.

Note: I am however running KDE in OpenSUSE on a pretty powerful box. Maybe someone who is also an expert in terminal knows a command/script to do this from the kernel?

Upvotes: 0

Views: 2811

Answers (2)

Dedek Mraz
Dedek Mraz

Reputation: 814

I suggest using a matlab.io.matfileclass objects on two of the files:

matObj1 = matfile('datafile1.mat')
matObj2 = matfile('datafile2.mat')

This does not load any data into memory. Then you can use the objects' methods to sequentialy save a variable from one file to another.

matObj1.varName = matObj2.varName

You can get all the variables in one file with fieldnames(mathObj1) and loop through to copy contents from one file to another. You can then clear some space by removing the copied fields. Or you can use a bit more risky procedure by directly moving the data:

matObj1.varName = rmfield(matObj2,'varName')

Just a disclaimer: haven't tried it, use at own risk.

Upvotes: 1

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33854

So on this site we usually would point you to whathaveyoutried.com but this question is well phrased.

I wont write the code but i will give you how I would do it. So first I am a bit confused about why you need to fread the file. Are you just appending one file onto the end of another?

You can actually use unix commands to achieve what you want:

files = dir('*.dat');
for i = 1:length(files)
    string = sprintf('cat %s >> output_final.dat.temp', files(i).name);
    unix(string);
end

That code should loop through all the files and pipe all of the content into output_final.dat.temp (then just rename it, we didn't want it to be included in anything);

But if you really want to use fread because you want to parse the lines in some manner then you can use the same process:

files = dir('*.dat');
fidF = fopen('output_final.dat', 'w');
for i = 1:length(files)
    fid = fopen(files(i).name);
    while(~feof(fid))
        string = fgetl(fid) %You may choose to parse the string in some manner here
        fprintf(fidF, '%s', string)
    end
end

Just remember, if you are not parsing the lines this will take much much longer.

Hope this helps.

Upvotes: 1

Related Questions