0

I have length(C) number of variables. Each index represents a uniqe type of variable (in my optimization model), e.g. wheter it is electricity generation, transmission line capacity etc..

However, I have a logical vector with the same length as C (all variables) indicating if it is e.g. generation:

% length(genoidx)=length(C), i.e. the number of variables
genoidx = [1 1 1 1 1 1 0 0 ... 1 1 1 1 1 1 0 0]

In this case, there are 6 generators in 2 time steps, amounting to 12 variables.

I want to name each variable to get a better overview of the output from the optimization model, f.ex. like this:

% This is only a try on pseudo coding
varname = cell(length(C),1)
varname(genoidx) = 'geno' (1 2 3 4 5 6 ... 1 2 3 4 5 6)
varname(lineidx) = 'line' (... 

Any suggestions on how to name the variables in C with string and number, based on logical ID-vector?

Thanks!

Martin K
  • 5
  • 1
  • 2
    No. You do not want these variables. This is called "using dynamic variable names" which is bad. Very bad. Just store everything in either a matrix or a cell-array. – Adriaan Oct 03 '15 at 16:26
  • It's even worse than bad, it's evil. – Ratbert Oct 03 '15 at 21:37

1 Answers1

0

Using dynamic names is maybe OK for the seeing the results of a calculation in the workspace, but I wouldn't use them if any code is ever going to read them.

You can use the assignin('base') function to do this.

I'm not quite sure what your pseudo code is attempting to do, but you could do something like:

>> varname={'aaa','bbb','ccc','ddd'}

varname = 

    'aaa'    'bbb'    'ccc'    'ddd'

>> genoidx=logical([1,0,1,1])

genoidx =

     1     0     1     1

>> assignin('base', sprintf('%s_',varname{genoidx}), 22)

which would create the variable aaa_ccc_ddd_ in the workspace and assign the number 22 to it.

Alternatively you could use an expression like:

sum(genoidx.*(length(genoidx):-1:1))

to calculate a decimal value and index a cell array of bespoke names:

>> varname={'aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'}

varname = 

    'aaa'    'bbb'    'ccc'    'ddd'    'eee'    'fff'    'ggg'    'hhh'

>> assignin('base', varname{sum(genoidx.*(length(genoidx):-1:1))}, 33)

which would create the variable ggg and assign 33 to it.

Erik
  • 812
  • 1
  • 7
  • 15
  • Thanks, Erik! Yes, the purpose of this is to easier evaluate an optimization problem in case of any infeasibilities. When you have thousands of variables and contraints, it is nice to have some ideas about what they represent. – Martin K Oct 06 '15 at 14:31
  • Hi Martin, Is my answer good enough to be marked as THE answer? I think it helps my SO profile/score etc.Thanks. – Erik Apr 21 '16 at 08:12