Load multiple variables into single excel file
1 Kommentar
The trick is to load into a variable (which is a structure):
S = load(...);
Once you have one structure S you can loop over its fieldnames, or perform operations on the whole structure.
Note: anytime that you find yourself trying to access lots of separate variables you are doing something wrong: keep data together as much as possible, because this makes processing it much simpler. One of the most important ways of achieving this is to load into an output variable, rather than simply spamming all of the variables in the .mat file directly into the workspace. Read this to know more:
Antworten (1)
You can refer to my answer to your other question to see how can you combine multiple tables into one. Now for this question, as far I understand, each mat file contains 31 tables and you have several mat files and you want to generate 1 excel file corresponding to each mat file. As suggested by @Stephen, it is better to load mat file into a struct to avoid any confusion. Your given code can be modified as follow
files = what('Extract_parameter'); %list all the mat.files in the folder
for i = 1:length(files.mat)
GenNum = files.mat{i}; %generator mat file
big_table = [];
tables = load (['Extract_parameter\' GenNum]); %load mat file into struct.
f = fieldnames(tables)';
for j=f
% here I am assuming that tables struct only contain tables class variables. Otherwise, you might want to add if class(tables.(j{:})) == "table" before next statement
big_table = [big_table; tables.(j{:}){:,:}]
end
big_table = cell2table(big_table);
writetable(big_table, ['myfile' num2str(i) '.xlsx']);
end
The above method will work even if all tables have different column names. This script will generate 'myfile1.xlsx', 'myfile2.xlsx', ... and so on, upto the number of mat files.
5 Kommentare
@Ameer Hamza Khan: given that i is a scalar cell containing a char vector, what does this do?:
num2str(i)
How did you test this code?
There was a mistake in my original answer, as pointed out by @Stephen. I made an edit to the posted code. You might be using the older version. Can you check if inner for loop have j=f instead of i=f. Also, it is a better MATLAB coding practice to use ii and avoid i as a variable name, as it already represents imaginary number iota and will cause errors if used carelessly.
Kategorien
Mehr zu Tables finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!