How can add a name of table by concatenating strings?

I have multiple matlab tables that at first I need load them to the matlab and then do some analysis. Assume they are saved with these names: tableA, tableB, tableC. I am interested to load all in one array by defining the name of tables in one array:
A=['tableA','tableB','tablesC']
so that I can write a for loop to load all arrays instead of writing load for each individual table. Sth like:
for i=1:size(A)
load(A(i))
end
and it wont work because A(i) are strings not the name of tables.
How can I solve this issue?
It is more genreal question. It happens to me in many cases that I need to make the name of table by strcat function.
How can I do that?

3 Comments

Rethink your strategy. Generating variable names on the fly is a bad idea.
I'm not sure why you require to do this because TUTORIAL: Why Variables Should Not Be Named Dynamically (eval) you can probably fix your problem by store all your tables in a cell array.
D = 'D:\whatever'; % select directory
filePattern = fullfile(D, '*.mat'); %or if you have .xlsx tables
file = dir(filePattern);
x = {};
for z = 1 : numel(file)
baseFileName = file(z).name;
fullFileName = fullfile(D, baseFileName);
x{z} = load(fullFileName); %or readtable if you have .xlsx tables
fprintf('read file %s\n', fullFileName);
end
then you can simply access each table using something like:
mytable = x(:,1)
let me know if it worked for you !
"It happens to me in many cases that I need to make the name of table by strcat function."
Forcing numbers or any other meta-data into variable names is a sign that you are doing something wrong:
"How can I solve this issue?"
Use arrays and indexing. You can trivially load into an output variable (which is a scalar structure):
S = load(...);
and then use indexing to allocate that array to a non-scalar structure or a cell array... and is exactly what the MATLAB documentation recommends:

Sign in to comment.

 Accepted Answer

Don't do that!
filenames = something appropriate ;
nfiles = length(filenames);
tcell = cell(nfiles, 1);
for k=1:nfiles
filestruct = load(filenames{k});
fn = fieldnames(filestruct);
tcell{k} = filestruct.(fn{1});
end
A = vertcat(tcell{:}) ;

12 Comments

is filenames equivalent to A=['tableA','tableB','tablesC']?
if yes, then you are doing the similar thing and load(filenames{k}) would get error.
Can you please say what does this piece of code do? or comment it?
for k = 1:20
% Create a mat filename, and load it into a structure called matData.
matFileName = sprintf('mat%d.mat', k);
if exist(matFileName, 'file')
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
A=['tableA','tableB','tablesC']
In MATLAB is equivalent to
A = 'tableAtableBtableC';
You would want something like
A = {'tableA.mat', 'tableB.mat', 'tablesC.mat'};
The code loops through a list of file names. For each one it loads the file into a structure. It takes the fieldnames of the structure and picks out the first of those. It extracts that structure field and stores it into a cell array. At the end of the loop it takes the content of the cell array and concatenates them all together into one object.
Loading into a structure is done because (A) "poofing" variables into existence is not good programming and causes problems and is being increasingly restricted by the MATLAB engine; and (B) because we do not know the names of the variables stored in the files, and cannot be certain that the file will have only one variable in it. The code resolves ambiguity by saying that it will take the first variable in the file. If that is not a good choice then you need to define how to decide which of the several variables in a file to pick.
@ Walter Roberson:
Now the names are strored in structures, how can I call the tables?
is load(filenames{k}) calling the table? how does matlab recognioze that we are loading the table?
When filenames is a list of mat files, then the code I posted will use load() to read the mat file and extract the first variable and store it in the cell array tcell. Then after the loop it concatenates all of those together into one variable as that was the original request, to create a single table out all of them. You examine the k'th table as tcell{k}
This code would not store the tables as individual variables by name the way you originally asked. We firmly recommend against doing that.
Oh let me clarify sth:
I already have tables. I have table A, B and C. I want to load them. Instead of writing load('tableA') and load('tableB') and load('tableC'), I want to add the name of the ables to an array and then in a for loop load the tables one by one.
I think the script you shared does sth different.
I already have tables. I have table A, B and C
It would be better if right from the start you had not created independent variables for those tables, and instead had stored them in a single variable such as a cell array or struct .
I want to add the name of the ables to an array and then in a for loop load the tables one by one
We firmly discourage that kind of programming. Behzad Navidi and Stephen Cobeldick have posted links to explanations of the problems with that kind of programming, links that demonstrate alternatives.
"Instead of writing load('tableA') and load('tableB') and load('tableC'), I want to add the name of the ables to an array and then in a for loop load the tables one by one."
That is exactly what Walter Roberson's answer does.
Thank you all. @ Walter Roberson: You are helpful as always. I really appreciate your suggestions for each of my questions.
@ Stephen Cobeldick
I wanted to make dynamic name for the table which is not recommended. Walter's code add dynamic name to structure not directly to the table (which is not recommended).
Hmmm, my code does not add dynamic names to the structure, or at least not deliberately, but I guess it would not be completely wrong to argue that the way I use load() is a use of dynamic field names. MATLAB automatically creates the field names in that case, rather than my deliberately creating them. I read from them rather than writing to them. If the variable names in the file were fixed then even this would not be needed.
"I wanted to make dynamic name for the table which is not recommended."
Correct: accessing variable names dynamically is not recommended by experienced MATLAB users, and is also very clearly discouraged by the MATLAB documentation:
"Walter's code add dynamic name to structure not directly to the table (which is not recommended)."
I don't see that advice anywhere in the MATLAB documentation. While it is certainly possible to misuse dynamically named fields (e.g. where a non-scalar structure with indexing would be simpler and more effiicient) in general I see no reason to avoid them, especially in your case when it is the much better option.
Most of the risks/disadvantages to dynamically naming variables, such as those I list here:
do not apply to dynamically named fields, perhaps efficiency could be relevant.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!