Using Strcat to create dynamic variable names

2019-01-28 20:51发布

问题:

I have a process which is repeated on a set of data stored in separate folders. Each time a certain folders data is processed I need new variable names as I need to results separate after the initial processing is finished for more processing. For example at the start of each new block of the repeated function I declare sets of arrays

Set_1 = zeros(dim, number);

vectors_1 = zeros(dim, number);

For the next set of data I need:

`Set_2 = .........`

and so on. There is going to be alot of these sets so I need a way to automate the creation of these variables, and the use the new variables names in the function whilst maintaining that they are separate once all the functions are completed.

I first tried using strcat('Set_1',int2str(number)) = zeros(dim, number) but this does not work, I believe because it means I would be trying to set an array as a string. I'm sure there must be a way to create one function and have the variables dynamically created but it seems to be beyond me, so it's probably quite obvious, so if anyone can tell me a way that would be great.

回答1:

I'd not do it like this. It's a bad habit, it's better to use a cell array or a struct to keep multiple sets. There is a small overhead (size-wise) per field, but it'll be a lot easier to maintain later on.

If you really, really want to do that use eval on the string you composed.



回答2:

The MATLAB function genvarname does what you want. In your case it would look something like:

eval(genvarname('Set_', who)) = zeros(dim, number);

However, I would follow the recommendations of previous answers and use a cell or struct to store the results.



回答3:

This sort of pattern is considered harmful since it requires the eval function. See one of the following for techniques for avoiding it:

  • http://www.mathworks.co.uk/support/tech-notes/1100/1103.html
  • http://blogs.mathworks.com/loren/2005/12/28/evading-eval/

If you insist on using eval, then use something like:

eval(sprintf('Set_1%d = zeros(dim, number);', number))


标签: matlab eval