MATLAB : Generate variable name and allot vector / matrix to it

Matlab provides a nice and simple way to generate continuous set of variable names, say in the form of var1, var2,… etc. This can be accomplished using genvarname and eval commands. Here i’ll show an example where we need to store columns of a matrix A in 3 vectors var1, var2 and var3. Following is the code snippet :

n = 3;                                         % say

A = [1 2 3;4 5 6;7 8 9];            %say

for i = 1:n

val = genvarname([‘var’ num2str(i)]);

eval([val ‘=A(:,i);’]);


And you are done.. the columns of A get stored in the vectors var1, var2 and var3. Similarly, even block matrices within A can be assigned this way. This is a much more elegant and faster way than doing the same thing via for-loops.