MATLAB Answers


How to save a function output to a variable with variable name changing dynamically?

Asked by hello_world on 13 Jul 2018
Latest activity Commented on by Walter Roberson
on 14 Jul 2018
I have two folders in two different paths. These two folders contain .csv data files. I want to load these .csv data files from each folder and fun PCA on them. I want to save output variable in a format so that I can keep track that from which data folder I imported those .csv files.
For example, in my code below, I have Data1 and Data2 folders containing these .csv files. In the first iteration of for loop, I will like to load .csv files from folder Data1, and save output variable from pca function as Data1_Name_PCA. For the second iteration, I will like to save the output variable from pca as Data2_Name_PCA, and so on.
Here _PCA is fixes. Only Data1_Name and Data2_Name should change for each iteration.
My code works fine, but I am trying to figure out how to save output of PCA on these dynamically changing names.
For testing my code below, you can use arbitrary .csv files.
Path1 = 'C:\Users\Anonymous\MATLAB\Data1';
Path2 = 'C:\Users\Anonymous\MATLAB\Data2';
DataFiles1 = dir(fullfile(Path1, '*.csv'));
DataFiles2 = dir(fullfile(Path2, '*.csv'));
Filename1 = {};
Filename2 = {};
filename = {Filename1, Filename2};
[rows, cols] = size(filename);
for i = 1:cols
data1 = importdata(filename{i}{1});
data2 = importdata(filename{i}{2});
data1_Name = filename{i}{1}(1:end-4);
data2_Name = filename{i}{2}(1:end-4);
[data1_Name_PCA, eigVec1_PCA, lambda1_PCA] = pca(data1, 3);


Do NOT do this. The MATLAB documentation specifically warns against doing exactly this: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Please do not close questions that have an Answer.
The output you desire is possible. We firmly recommend against it.

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 13 Jul 2018
 Accepted Answer


@Walter Roberson: Yeah ok, it will work. But I really wanted to have an output variable as data1_Name_PCA rather than all_data.(fieldname1). Let me see if some other possibility before accepting your answer.
I appreciate your help though!
If you follow the link above, you will find links to information on how it is possible to create variable names dynamically. However, we really do not recommend it.
"But I really wanted to have an output variable as..."
Sure, we understand what you want. And we are advising you, that that approach is not recommended by any MATLAB experts, experienced MATLAB users, or by the MATLAB documentation. Wanting code to do a particular thing does not correlate with it being a good idea, nor with it even being tractable at all, which is why we are giving advice on how to write better code:

Sign in to comment.