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);’]);

end

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s