Create a separate new variable for each element of a vector.

I have a vector z_ss, and I need to create new variables which I call zss_i, where zss_i= z_ss(i). That is , if z_ss is 3-by-1, I want to create zss_1 = z_ss(1), zss_2= z_ss(2) and zss_3 = z_ss(3). How can I do that in a general way?
Thanks.

3 Comments

" I need to create new variables which I call zss_i..."
Why? Doing this will make your code pointlessly complex, slow, buggy, hard to debug, obfuscated and insecure. Some beginners think that magically creating or accessing variables names is the best way to solve some task, but actually it just makes code slow, buggy, and complex. Read this to know more:
What prevents you from using indexing, which is simple, neat, and extremely efficient? Once you learn to keep all of your data in one array then using MATLAB efficiently is very simple because you can easily write vectorized code and process all of your data with single commands.
I need to use each of them in dynare, and dynare cannot handle vectors
zss_1 = ss(1);
zss_2 = ss(2);
zss_3 = ss(3);
But don't do it.

Sign in to comment.

Answers (1)

E.g., if you really need to do this for some non-MATLAB reason:
for k=1:numel(z_ss)
eval(sprintf('z_ss_%d = z_ss(%d);',k,k));
end
Or, if you want to use a specific number of digits for the ending number, then e.g.
for k=1:numel(z_ss)
eval(sprintf('z_ss_%03d = z_ss(%d);',k,k));
end
This will "poof" the variables into your workspace, which is generally not a good thing to do. Dealing with them downstream in your code, as Stephen cautions, is also not fun.
Are you sure you don't simply need to write these variables to a file in a certain format for some other application to read?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 10 Nov 2017

Commented:

on 10 Nov 2017

Community Treasure Hunt

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

Start Hunting!