How can add a name of table by concatenating strings?
Show older comments
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
Rik
on 31 Jan 2020
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 !
Stephen23
on 1 Feb 2020
"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:
Accepted Answer
More Answers (0)
Categories
Find more on Structures 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!