Define a text string and use in variable name throughout script

3 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 10 Apr 2016
See my answer to know why you should not access variable names dynamically.

Accedi per commentare.

Risposte (2)

Stephen23
Stephen23 il 7 Apr 2016
Modificato: Stephen23 il 19 Giu 2019

jgg
jgg il 7 Apr 2016
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)))

Community Treasure Hunt

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

Start Hunting!

Translated by