MATLAB Answers

How to make dynamic variable names (A1, A2, ..., An) with "for" loop? Using "eval" "num2str"?

2,236 views (last 30 days)
Italo on 13 Nov 2013
Edited: Stephen on 20 Sep 2021
Hello community,
my knowledge of Matlab is limited, I admit it. So, I am sorry if I am going to make mistakes.
I have to create a series of variable using a "for" loop.
I make this:
for i=1:3
eval(['A' num2str(i) '= i'])
and it works well, it makes 3 variables A1, A2, A3.
But I need to use this variables to make other variables B1, B2, B3 where Bi=Ai*i. So I should have B1=A1*1=1, B2=A2*2=2*2=4, B3=A3*3=3*3=9
I tried something like this:
for i=1:3
eval(['A' num2str(i) '= i'])
eval(['B' num2str(i) '= 'A' num2str(i) '*i])
but it gives me error and it doesn't work. Of course I simplified things, the real code is a bt more complicated but I need to know the basics of how this could work.
Thank you
Stephen on 6 Jul 2020
"...unbalanced or unexpected parenthesis or bracket error has occurred in second eval. Why??"
Looking at the character vector shows at least one obvious syntax error (which looks like an implicit multiplication, but without any code comments, this is just a guess), which is quite possibly the cause of that error. There might be more syntax errors.
"Please explain me"
If this code had been written better** using basic indexing then the location of any syntax errors would get highlighted by the MATLAB Editor, and the code would be much easier to debug. So whoever wrote that code chose an approach which forces the user into writing slow, complex, buggy code which is hard to debug. Now you are finding that (otherwise very simple) code is buggy and hard to debug, which will come as no surprise to any readers of this forum (or for that matter to anyone who reads the MATLAB documentation).
** better in the sense simpler, neater, faster, more efficient, less buggy, easier to debug, e.g. by using basic indexing.

Sign in to comment.

Accepted Answer

Stephen on 12 Jan 2016
Edited: Stephen on 19 Jun 2019
Giovanni Barbarossa
Giovanni Barbarossa on 27 Jun 2018
Hello, I have a similar need deriving from what it seems to be a limitation of the Classification Learner app. I am generating a cell array of tables with my program and want to try each of the tables as training features in the Classification Learner, but the app does not see cell arrays in the workspace. I do understand it's a bad idea to generate dynamic variable names, but what's the solution to my need? Thanks

Sign in to comment.

More Answers (4)

Amit on 22 Jan 2014
Edited: Amit on 22 Jan 2014
Italo, I am glad you're trying out things on matlab.
Matlab is very good with matrixes. What you're doing in these can be done much easily. For example:
A = 1:3;
B = A.*A; %
You can find many tutorials online on how to use MAtlab. For example:

Jerry Olup
Jerry Olup on 28 Apr 2018
Edited: Jerry Olup on 28 Apr 2018
I did find dynamically named variables useful for a specific need. I have several files in a directory. Each file has a few columns that are read into a structure. It's convenient to read and simultaneously name the variables per a filename. For instance I read to a temp var then use the ill-advised exec capability to assign this to a variable specific to the file I read in. Looping, I read all files in the dir efficiently. 'files' is a cell array of file names discovered in that directory....
tmp = table(dataArray{1:end-1}, 'VariableNames', {'max_mag','max_noise','max_cnt'});
eval([files{i} '=tmp'])
I do see where this is not good for general variable naming, but I believe there's a niche usage in this case. Opinions? Best, Jerry
Jerry Olup
Jerry Olup on 12 Aug 2018
Hi Stephen, I'll give the idea of provide parallel constructs where the file-specific variable references are in one cell while data is collected in structure. I've shifted in the last month or so to use python for preprocessing - so this problem has largely gone away and been replaces with xlsread, csvread etc.
>>files data are not restricted to valid field/variable names
My file names are conventionally, ascii with underscores and timestamps yyyymmdd_hhmmss type, so I do see where this is problem. They are pretty specific so I thought I was giving a concrete counter example in contrast to @Italo and @Muna, who started this thread naming generic matrices.
>>you have not given any reason why none of those methods would work.
You're absolutely correct. I latched onto that solution as it was elegant for what I needed.
Thanks for the interaction, best, Jerry

Sign in to comment.

César Silva Proaño
César Silva Proaño on 12 Aug 2018
Hi, look I was doing something similar in order to create a function with the Krammer Method, for solving any size of matrix-equation problem. Look I created a function in order to do this, therefore, I needed to do it automatically, creating variables dinamically. Look at this fucntion.
function [ X ] = funcionMetodoKrammer( A )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
% ex: A = [-3 2 1 10;5 -8 3 15;-8 -9 10 20];
sizeA = size(A);
sizeFilasA = sizeA(1,1);
sizeColumnasA = sizeA(1,2);
matrizASinResultado = A(1:sizeFilasA,1:sizeFilasA);
matrizResultados = A(:,sizeColumnasA);
if (sizeFilasA == sizeColumnasA - 1)
for (i = 1:sizeColumnasA)
genvarname('matrizColumna', num2str(i));
eval(['matrizColumna' num2str(i) '=A(:,i)']);
for (i = 1:sizeFilasA)
genvarname('matrizTemporalColumna', num2str(i));
eval(['matrizTemporalColumna' num2str(i) '=matrizASinResultado(:,i)']);
matrizIncognita1 = [matrizResultados,matrizASinResultado(:,2:sizeFilasA)];
for (i = 2:sizeFilasA)
genvarname('matrizIncognita', num2str(i));
eval(['matrizIncognita' num2str(i) '=[matrizASinResultado(:,1:i-
msgbox('La matriz ingresada para el método Krammer es incorrecta');
for (i = 1:sizeFilasA)
genvarname('X', num2str(i));
genvarname('matrizIncognita', num2str(i));
eval(['X' num2str(i) '= det(matrizIncognita' num2str(i) ')/det(matrizASinResultado)']);
X = zeros(1,sizeFilasA);
for (i = 1:sizeFilasA)
genvarname('X', num2str(i));
eval(['X' '(1,' num2str(i) ')=X' num2str(i)]);
Asuminedo que existen variables B1, B2 y B3 se pueden acceder a las
variables de la siguiente manera
B1 = 10; B2 = 11; B3 = 12;
for (i = 1:3)
genvarname('Prueba', num2str(i));
genvarname('B', num2str(i));
eval(['Prueba' num2str(i) '=' 'B' num2str(i) '+10']);
I strongly disagree with the idea that you shouldn't use this because, if it exists I mean why not? It is not prohibited, and additionally it is very helpful in some cases.
jonas on 11 Sep 2018
"you just attack this method and you do not present an formal solution"
This is simply untrue. On the contrary, from what I've seen Stephen always provides a concrete solution when possible. Here's an example from 5 minutes ago ( link ) which is nothing out of the ordinary.
"But please make us all a favor and present a code, not just words or links..."
This is the mindset I see in a lot of younger students today - avoid instructions like the plague and feel entitled to a solution. Remember that no one is getting paid to read about your dynamic variables, so you should appreciate any replies including links and words (whatever that means).

Sign in to comment.

Gabor on 20 Sep 2021
eval(['Dynamic_var_name_' datestr(Date,'mm_dd_yyyy') '=T;']);
This is how you name dynamically a variable or a table or a cell or anything regardless if it is recommended or not.

Community Treasure Hunt

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

Start Hunting!