For loop extracting variable

6 views (last 30 days)
DripDrip1521
DripDrip1521 on 13 Apr 2020
Edited: Stephen23 on 13 Apr 2020
I am trying to extract data from different data files. In each data file i have an amplitude that is different but want to pull out that data file and name it a different name for each time i run the loop.For example, i have four files names "lab_test_1, lab_test_2, lab_test_3, lab_test_4" and within each of these files i have a variable named 'amplitude'. Is it possible within a for loop to extract each amplitude renaming it to the lab # i pulled it out from? Example: "amplitude_1", "amplitude_2" and so on.
  1 Comment
Stephen23
Stephen23 on 13 Apr 2020
Edited: Stephen23 on 13 Apr 2020
'Example: "amplitude_1", "amplitude_2" and so on.'
That is exactly what you should NOT do. Dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
The MATLAB documentation shows how to efficiently use one cell array with simple indexing:
You should use indexing, it will make your code simpler and much more efficient.

Sign in to comment.

Answers (1)

Peng Li
Peng Li on 13 Apr 2020
Not quite sure your data type. So below just a structure that you can potentially use.
within the for loop
for iF = 1:yourFileNumbers
...
...
% above stuff you need to load your data
% you get the amplitude
% and rename it
eval(['amplitude_' num2str(iF) ' = amplitude;']);
end
But actually people are against of generating many variables as it is loose and slow. Better make amplitude a field of your lab_test_ data using structure or table. You could easily access amplitude by dot indexing.
  3 Comments
Peng Li
Peng Li on 13 Apr 2020
you can make it an element of a vector.
for example you have four files
b = nan(1, 4);
for iF = 1:4
...
...
b(iF) = amplitude;
end
Stephen23
Stephen23 on 13 Apr 2020
"But actually people are against of generating many variables as it is loose and slow."
But actually the MATLAB documentation is against generating many variables as it is complex and very inefficient. "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."

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!