Using 'Char' Information As A Variable Name

15 views (last 30 days)
Bugrahan Guner
Bugrahan Guner on 14 Feb 2022
Answered: Stephen23 on 14 Feb 2022
I aim to load a couple of .mat files consisting of different arrays and variables with the same names. I will use a loop for this purpose. Since all files consist of variables with the same names, after every file is loaded inside a for loop, the variables and arrays will be assigned to different variables and arrays. For instance 'force' arrays inside file1, file2 and file3 will be assigned to new arrays named force_file1, force_file2, force_file3. I want to store file names in 'char' format to adjust the names of other variables in the loop. So for file1, the name of the file 'file1' will be stored and the new variable names, like the force_file1, will be created automatically using the file's name. Basically, i want to autoamtically create a file name by using a stored 'char' information.
I am also open for other suggestions.
Thank you in advance for your help and time.

Answers (2)

Walter Roberson
Walter Roberson on 14 Feb 2022
I would not recommend that at all.
Use the form of load() that has an output argument. The result will be a struct with one field for each variable loaded. You can store that struct in a struct array (or cell array if they might not all have the same variables.)

Stephen23
Stephen23 on 14 Feb 2022
That would be complex and very inefficient. Your suggested approach is best avoided.
A much simpler approach is to store the imported data in one container array (e.g. a cell array or a structure), which after importing the files can be trivially concatenated into one structure array if so desired. For example:
P = 'absolute or relative path to where the files are saved':
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = load(F);
end
D = [S.data] % optional

Categories

Find more on Variables 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!