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
" 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.
Adelia
2017년 11월 10일
John D'Errico
2017년 11월 10일
zss_1 = ss(1);
zss_2 = ss(2);
zss_3 = ss(3);
But don't do it.
답변 (1개)
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에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!