Using Strcat to create dynamic variable names

2019-01-28 20:34发布

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.

标签: matlab eval
3条回答
Melony?
2楼-- · 2019-01-28 21:14

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.

查看更多
太酷不给撩
3楼-- · 2019-01-28 21:23

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

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

eval(sprintf('Set_1%d = zeros(dim, number);', number))
查看更多
放荡不羁爱自由
4楼-- · 2019-01-28 21:30

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.

查看更多
登录 后发表回答