Using Strcat to create dynamic variable names

▼魔方 西西 提交于 2020-03-12 04:45:16

问题


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))


来源:https://stackoverflow.com/questions/9082031/using-strcat-to-create-dynamic-variable-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!