MATLAB- Individually Saving Workspace Variables into Many Individual .mat Files - matlab

So I have many files in a MATLAB workspace all in the same format,
"project1day1", "project1day2" etc. and instead of having them all in the same workspace, I want to save them as their own individual .mat files with the same name.
So, I want the "project1day1" variable in the workspace to go to a "project1day1.mat" file.
I have 7 projects, and all of them except for project 1 has 3 "days". I was having trouble executing the exact syntax to do it. I want to loop through my workspace data in a general fashion. I want to execute something along the lines of:
maxdays=3;
maxprojects=7;
for i = 1:maxprojects;
for j = 1:maxdays;
save('project%dday%d','project%dday%d,i,j,i,j)
end
end
Two things:
1) The save option isn't working
2) I need to include some sort of ~if(exist '...') for the case where there isn't a 3rd day, but I'm having trouble doing so.

As rayryeng wrote, I think in most cases it would be better to either save the variables in one file, or (you wrote they are all in the same format) use a structure or a cell array, which makes it much easier to access them later.
If you really need to save all variables in the workspace to separate files you can do something like this:
vars = who;
for i=1:length(vars)
save([vars{i} '.mat'], vars{i});
end
But again, I wouldn't do this if it is not (for some reason) absolutely necessary!

Related

How to save the matlab workplace variable including original file name?

I would like to know how I can save the matlab output files (i.e. matlab workplace variables), by including original file name.
e.g. I open a file (filename.mat) with load filename.mat. Then I run a code to do calculation and I get some workplace variables (e.g. flow, pressure). I want to save those variables as filename_flow.mat and filename_pressure.mat.
I will use the same code on different filename, so I would like to know how I can save my variables as mentioned above (i.e. including the original file's name)?
FileToBeLoaded = 'filename.mat';
[pathstr,filename,ext] = fileparts(FileToBeLoaded)
load([filename ext]);
%// calculate stuff
FlowVariable = %// some calculation
save([filename '_flow'],FlowVariable)
The same of course works for other names as well. You pull apart the original file name to its actual name and extension, and use the original name, add something (_flow in this case) and save that. The default of MATLAB is already to save to a .mat file, so that's taken care of automatically.

How to create blank .mat file from terminal?

Is there any way to create an empty .mat file from a terminal session? Basically, what I am doing is brain graph analysis. The software I am using, if an entire brain is scrubbed (ie, if the displacement of the brain is greater than a certain threshold) the output file will be left out or will be very small. When analyzing, however, I need to be able to eliminate both subjects from the analysis if the entire brain is scrubbed/too much of the brain is scrubbed. To accomplish this, the easiest way would be to simply check the dimensions of the output file within matlab, and if they are below the arbitrary threshold I decide then both subjects will just be skipped over for analysis. The issue is, I can easily check if a file contains too few remaining frames, however, if the resulting file contains no frames, it will entirely just not exist. As the outputs are all sorted, the only thing I need to do is check consecutive files' dimensions, and if one of the files does not contain enough values, then I can simply skip over it entirely. Simply touching a blank file obviously will not work, since it will not contain any encoding. I hope this is a good explanation for my motivation to do this, and if any of you know of any suggestions, please let me know.
A simple solution would be to create an empty file from Matlab and duplicate the file when needed from the console.
Just open Matlab, set to the destination folder and type this:
clear all
save empty.mat
Then, when needed, copy the file from the console. :)
Saving the contents of an empty struct creates an empty .mat file:
emptyStruct = struct;
save('myFile.mat','-struct','emptyStruct');

Script for running (testing) another matlab script?

I need to create a matlab mfile that will run another matlab file with default values given in a txt file. It's ment to be useful for testing programs, so that user may specify values in a txt files and instead of inputing values every time he starts the program, my script will give the program default values and user will only see the result.
My idea is to load tested file into a variable, change 'variable=input('...');' for variable = default_variable;, save it to tmp file, execute, and than delete tmp file. Is this going to do the job?
I have only two problems:
1) How to eliminate the problem of duplicated variable names - i mean this must work for all scripts, i don't know the names of variables used in tested script.
2) As I wrote before - is this going to work fine? Or maybe I missed a easier way to do it - for example maybe I don't have to create a tmp file?
I really need your help!
Thanks in advance!
If the person who has to edit the default values has access to Matlab, I would recommend saveing the values in a mat file and loading them when needed. Otherwise you could just write a smalls cript that contains the assignment to certain variables, but make sure to keep this small. For example:
maxRuns = 100;
clusters = 12;
So much for setting up the defaults. Regarding the process my main advice is to wrap the thing that you want to test into a function. This way variables used in the code to call the 'script' will not interfere as a function gets its own separate workspace. Check doc function if you are not familiar with them.

Load multiple .mat files for processing

In MatLab I have (after extensive code running) multiple .mat files outputted to .mat files. The actual matlab name of each .mat file is called results but I've used the save command to write them to different files. A small subset of the files looks like this:
results_test1_1.mat
results_test1_2.mat
results_test1_3.mat
results_test1_4.mat
results_test2_1.mat
results_test2_2.mat
results_test2_3.mat
results_test2_4.mat
Now I want to compare the results for each test, which means I have to load in all four .mat files and combine them in a graph. Reading in one file and making the eventual graph is no problem. But since all files have the same matlab name results, iteratively loading them is not an option (at least, not one that I know of yet) since in the end only file 4 remains since it rewrites the previous ones.
Is there a way to load all these files and store them in different variables in a structure (regarding only one test set)? Because doing all this manually is a hell of a lot of work.
I've tried to use this method: Load Multiple .mat Files to Matlab workspace but I get an Invalid field name error on loaded.(char(file)) = load(file);
You can load into a variable (preferably a cell array)
results = cell( 2, 4 ); % allocate
for testi=1:2
for resi = 1:4
filename = sprintf('results_test%d_%d.mat', testi, resi );
results{testi,resi} = load( filename );
end
end
Now you have all the results stored in results cell array and you may access the stored variables, e.g.,
results{1,3}.someVar % access variable someVar (assuming such variable was saves to the corresponding mat file

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:
12 seperate .dat files, each titled something like output_1_x.dat, output_2_x.dat, etc.
each file is actually one piece of a whole that was seperated and processed
each .dat file is approx. 3.9 GB
Here's what I need to do:
create a single file containing all the data from each seperate file, i.e. I need to recreate the original file.
call this complete output file something like output_final.dat
it has to be done in MATLAB, there are no other alternatives (actually there maybe; see note below)
What is implied:
I will have to fread each 3.9 GBfile into chunks or packets, probably 100 mb at a time (using an imbedded loop?)
these packets will have to be read then written sequentially
after one file is read then written into output_final.dat, the next file is automatically read & written (the master loop).
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?
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.
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.