Dynamic variable name change using Matlab

There are plenty of times in the past that I needed to store many different data srtuctures in different file names but I didn’t know the way to change the name of a variable during the execution of the code.

So now that I really needed to do so (storing 1500 different matrices one by one takes some time so naming them automatically while calculating them makes it much more efficient!) I searched the Matlab capabilities and found exactly what I was looking for!

Thus if for example you have table A and you want to store 10 different instances of the table like A_1 – A_10 then the eval() function is just what you need:

Here is the code that would do the trick:

 
for ii = 1 : 10
    % Creating the filename
    filename = [‘A_’ num2str(ii)];

     % Creating the new variable name
    varname = [‘A_’ num2str(ii)];
    
    % calculating the new value of A
    value = function(); 

    % This is the instruction that will assign the value to A_ii
    s = [‘A_’ num2str(ii) ‘= value ‘];
    
    % Do not use eval with no reason because it is much slower than the normal assignment.
    eval(s) ; 
    
    % Saving the result
    save(filename,varname)
end

Now lets say that we have 10 .mat files that need to be read from (the A_1 – A_10) here is how to do it:

for ii = 1 : 10
    eval(‘load A_’ num2str(ii))
end

Although the following might work as well:

for ii = 1 : 10
    filename = [‘A_’ num2str(ii)]; % Creating the filename
    load filename
end

but I’m not sure…

So have fun storing but take into account that it will affect the whole performance so use with care!

Advertisements