I have a variable a = 1
. I want to generate a variable name of the form:
variableNumber
So in this example, I would want
My answer to this question is "Are you sure you really want to do that?"
If you have a series of variables like this, you are then going to have to figure out a way to refer to all those variables later, that will likely mean an EVAL or something else like that.
If you know that everything you will store in this will be a scalar, you could store them all in a vector:
a(1) = 1;
a(2) = 2;
a(3) = 3;
What if you do not have scalars?
a{1} = 1;
a{2} = 'Doug';
a{3} = [1 2 3 4];
Then you can refer to these as a{1} or whatever.
Unless you have a good reason to do this, you are better off making a cell array, array of structures, vector, or something else.
My answer to this question is "Are you sure you really want to do that?"
But if your answer is YES then that is your answer:
for k=1:5
eval(['a' num2str(k) '= k;'])
end
Use assignin
.
assignin('base', sprintf('variable%d', 1), 1:10)
EDIT: As JS mentioned, structs are generally better for dynamic field names. You can use them like this:
varnames = {'foo', 'bar'};
str = struct;
for i = 1:length(varnames)
str = setfield(str, varnames{i}, rand); %#ok<SFLD>
end
str =
foo: 0.4854
bar: 0.8003
Or even more simply, like this:
str2.('alpha') = 123;
str2.('beta') = 1:10;
Try genvarname
.
varname = genvarname(str)
is the basic syntax for use. MATLAB documentation has detailed examples of using this function with an exclusion list (for ensuring unique variable names). You will have to use eval
or another function (e.g. assignin
, mentioned in an earlier answer) to utilise this variable name.
To answer the question completely,
varnamelist = genvarname({'a','a','a','a','a'});
for l=1:length(varnamelist)
eval([varnamelist{l} '= l^2']);
end
Of course, there are more efficient ways of putting together an input list for genvarname
, this is left as an exercise ;)
If you're concerned about performance, note that eval
may slow down the script/function greatly; personally I would recommend the use of struct or cell datatypes if you need dynamic variable naming.
I've been using this code for an application with Bootstrap neural networks
% k fold test with automatic division of data
warning off
% read in X
% read in T
% perform k fold division of input time series called 'K-fold Cross-Validation
% Bootstrap'
CVO = cvpartition(X,'k',10); % creates 10 sub samples of 'X' and divides it into 'training (i.e training and validation)' and 'testing' sets
for i = 1:CVO.NumTestSets
eval(['xtv' num2str(i) '=X(CVO.training(i));']) % cross-validation training sets of 'X'
eval(['xt' num2str(i) '=X(CVO.test(i));']) % cross-validation testing set of 'X'
eval(['ttv' num2str(i) '=T(CVO.training(i));']) % cross-validation training set of 'T'
eval(['tt' num2str(i) '=T(CVO.test(i));']) % cross-validation testing set of 'T'
end