Create single structure array with variables in for loop.
Show older comments
Hello, I am processing a series of text files that I then need to save the variables in each iteration for further manipulation within Matlab. I have followed the Matlab FAQ Wiki to process the files as shown below and save variables at each iteration. What happens, however, is that I create a separate .mat structure array for each file, which I then need to index the data out of:
data1 = load('myfilename1.mat')
data1 = data1.x
data2 = load('myfilename2.mat')
data2 = data2.x
What I would like to to do is create a single .mat structure array file where each string array within the structure array is the file name. So, for example, that would make loading the processed files easy, like this:
alldata = load('alldata.mat')
data1 = alldata.myfilename1
data2 = alldata.myfilename2
data3 = alldata.myfilename3
etc.
Thanks very much, here is my current code below, which works fine but is then incredibly clunky to load the data back into Matlab. Actually, I would prefer to not even save the files and just load the variables into the workspace with the filenames, but from my understanding, that is not recommended.
% Specify the folder where the files live.
myFolder = 'H:\mypath';
% Check to make sure that folder actually exists, warn if it does not.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.txt');
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Import data as character string
x = fileread(fullFileName);
x = cellstr(x);
% do a bunch of manipulations removed here for clarity
% convert data to string arrays
x = string(x);
% name and save as a .mat file
name = strrep(baseFileName,'.txt','.mat');
save(name,'x')
end
1 Comment
Luke McLellan
on 17 Jul 2018
You could try creating a cell of arrays for your data and then implement something along the lines of
Cell_Matrix = zeros(x,y);
for z = 1:length(Cell)
Cell_Matrix(z,:) = Cell{1,z,:};
end
Accepted Answer
More Answers (0)
Categories
Find more on Database Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!