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

Stephen23
Stephen23 2017년 11월 10일
편집: Stephen23 2017년 11월 10일
" 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.

댓글을 달려면 로그인하십시오.

답변 (1개)

James Tursa
James Tursa 2017년 11월 10일
편집: James Tursa 2017년 11월 10일
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?

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2017년 11월 10일

댓글:

2017년 11월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by