Define a text string and use in variable name throughout script

10 views (last 30 days)
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=:
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)
Stephen23 on 10 Apr 2016
See my answer to know why you should not access variable names dynamically.

Sign in to comment.

Answers (2)

Stephen23 on 7 Apr 2016
Edited: Stephen23 on 19 Jun 2019

jgg on 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!