Define a text string and use in variable name throughout script

3 ビュー (過去 30 日間)
Grant
Grant 2016 年 4 月 6 日
編集済み: Stephen23 2019 年 6 月 19 日
I have the following script. d181_b1, d181_b2 and d181_b3 are matrices. d181 indicates the 181st day and I want to quickly edit the script and rerun it for different days, e.g. d175. Currently I'm editing all six of those lines (and more not displayed) for each day I choose to run it. I'd like to be able to define the day in one line at the beginning of the script.
band1 = d181_b1;
band2 = d181_b2;
band3 = d181_b3;
clear d181_b1;
clear d181_b2;
clear d181_b3;
I tried, so I could just edit what day=:
day='d181'
band1 = [day '_b1'];
band2 = [day '_b2'];
band3 = [day '_b3'];
but this runs and returns band1 etc. as character variables, it doesn't define them as the numerical matrices db181_b1 etc. I've searched on this but not found an answer, perhaps I'm not using the correct terminology. Thanks. (I realise I could do find and replace, but seems useful to know how to script it)
  3 件のコメント
dpb
dpb 2016 年 4 月 7 日
編集済み: dpb 2016 年 4 月 7 日
Stephen23
Stephen23 2016 年 4 月 10 日
See my answer to know why you should not access variable names dynamically.

サインインしてコメントする。

回答 (2 件)

Stephen23
Stephen23 2016 年 4 月 7 日
編集済み: Stephen23 2019 年 6 月 19 日

jgg
jgg 2016 年 4 月 7 日
You can do this using the eval command, but you should AVOID it if possible. If there's any way to change the way those matrices are stored, do it. eval is evil.
d181_b1 = 10; %example data
d181_b2 = 11;
day = 181;
band = 1;
eval(strcat('band',num2str(band),' =','d',num2str(day),'_b',num2str(band)))
band = 2;
eval(strcat('band',num2str(band),' =','d',num2str(day),'_b',num2str(band)))

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by