creating a dynamic variable name based on cell array
Show older comments
Hello.
I have a simple problem, and that is that I want to create a variable name, that will store a table I am returning from a function I have previously created.
So I know this is not recommended, but I have a very specific reason I want to do it this way, and I do not want to store these tables I am returning into any type of structure. I have a specific need to assign them into a particular variable name.
My code is below. I would like to be able to assign the last line in that for loop, to the value, which is essentially the first 10 chars of the 'myFileNames' var on each iteration. I.e., the first time through the loop, it will be "H4_AUD_CAD". The next the var name should be "H4_AUD_JPY," and so on.
The first section below labeled, "THIS WORKS, but requires manual input," this works the way I want, but I have to manually input the the data in.
The section below that labeled, "Main Loop of Program to Loop through Each and THIS DOES NOT WORK" does not work, but is what I am aiming for, so that the only thing I need to update manually, is the first code block where I change the size of 'myFileNames,' and add in the additional .csv file I plan on manipulating. There will be dozens of these.
I have attached a zip file of my workspace. The non-working part is uncommented, and the working part is commented out. I have also attached an image I hope helps explain what I am trying to do.
clear all;
close all;
%% ===== Create Array of Data to Manipulate ================
myFileNames = cell(3,1);
myFileNames{1} = 'H4_AUD_CAD_050319.csv';
myFileNames{2} = 'H4_AUD_JPY_050319.csv';
myFileNames{3} = 'H4_USD_CAD_050319.csv';
%% ===== THIS WORKS, but requires manual input ================
fileName = char(myFileNames(1)); %Change this NUMBER HERE.
myChar = char(fileName(1:9) );
H4_AUD_CAD = importFunc(fileName, 2, 10000, myChar ); %Must RENAME VAR name here too
%% ===== Main Loop of Program to Loop through Each and THIS DOES NOT WORK ================
for k = 1:length(myFileNames)
fileName = char(myFileNames(k));
myChar = char(fileName(1:10) );
H4_AUD_CAD = importFunc(fileName, 2, 10000, myChar );
end
1 Comment
Accepted Answer
More Answers (1)
Gabor
on 20 Sep 2021
0 votes
T=table;
Date=datetime(2014,12,31);
eval(['Dynamic_var_name_' datestr(Date,'mm_dd_yyyy') '=T;']);
This is how you name dynamically a variable or a table or anything regardless if it is recommended or not.
Categories
Find more on Logical 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!