Define a text string and use in variable name throughout script

2 visualizaciones (últimos 30 días)
Grant
Grant el 6 de Abr. de 2016
Editada: Stephen23 el 19 de Jun. de 2019
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 comentarios
dpb
dpb el 7 de Abr. de 2016
Editada: dpb el 7 de Abr. de 2016
Stephen23
Stephen23 el 10 de Abr. de 2016
See my answer to know why you should not access variable names dynamically.

Iniciar sesión para comentar.

Respuestas (2)

Stephen23
Stephen23 el 7 de Abr. de 2016
Editada: Stephen23 el 19 de Jun. de 2019

jgg
jgg el 7 de Abr. de 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)))

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by