Load .mat file into a structure and changing the structure
48 views (last 30 days)
Show older comments
Hi I am new in matlab, I have load several .mat file with the following structure: SigTime, Signals2Load, Sigs. In SigTime there is the time in second, in Signals2Load there are the name of the signals and in Sigs there are the signals acquired. In the attachment you can find a screen of the structure. When I load these files I want to load it into a structure with in the header of the table the Signals2Load of each variables including the variable time and in every cell the signals. This is the loading code, but I can not understand how to change the structure.
%loading data
MatFolder='C:\Myfolder\';
filePattern = fullfile(MatFolder, '*.mat');
listMAT = dir(filePattern);
for i = 1 : length(listMAT)
baseFileName = listMAT(i).name;
fullFileName = fullfile(listMAT(i).folder, baseFileName);
Data(i)=load(fullFileName);
end
How I can do it?
Thanks
Answers (1)
prabhat kumar sharma
on 14 Feb 2024
Hi Emrico,
I understand that you want to load the .mat files into a structured format where the Signals2Load are the header names and the Sigs are the data, you can use a combination of struct and table in MATLAB.
The following code snippet should help you achieve this:
% Define the folder where your .mat files are located
MatFolder = 'C:\Myfolder\';
% Get a list of all .mat files in the folder
filePattern = fullfile(MatFolder, '*.mat');
listMAT = dir(filePattern);
% Preallocate a structure array to hold the data from each file
Data = struct();
% Loop through each .mat file
for i = 1:length(listMAT)
baseFileName = listMAT(i).name;
fullFileName = fullfile(listMAT(i).folder, baseFileName);
% Load the .mat file data
loadedData = load(fullFileName);
% Extract the variables from the loaded data
SigTime = loadedData.SigTime;
Signals2Load = loadedData.Signals2Load;
Sigs = loadedData.Sigs;
% Create a table with time and signals
% The '+1' accounts for the time column we will add
variableNames = ['Time', Signals2Load];
variableData = [SigTime, Sigs];
% Create a table with the specified variable names and data
Data(i).Table = array2table(variableData, 'VariableNames', variableNames);
end
So, Data will be a structure array where each element contains a table (Data(i).Table) corresponding to each .mat file. The table will have the time and signals as columns, with the signals named according to Signals2Load. You can access each table using Data(i).Table where i is the index of the .mat file in the Data structure array.
I hope it helps !
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!