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!