0

Possible Duplicates: How to concatenate a number to a variable name in MATLAB? MATLAB: How can I use a variables value in another variables name?

I have the following code:

x = textread('/home/data/data.txt','%s')
for i=1:50
    S=load(['/home/data/',x{i},'_file.mat'])
    info_',x{i},' = strcat(S.info1, S.info2)
end

Of course, the last line (info_',x{i},' = strcat(S.info1, S.info2)) doesn't work. It just doesn't seem to be possible to use a variable to create MATLAB elements. Is this right or am I just doing something wrong here? Is there an elegant workaround?

Community
  • 1
  • 1
Mike
  • 47
  • 1
  • 1
  • 5
  • 1
    Wow, looks like one of those hyper-duplicates: [How to concatenate a number to a variable name in MATLAB?](http://stackoverflow.com/questions/2809635), [Using MATLAB loop funtion to name calculate variables](http://stackoverflow.com/questions/3143959), [Matlab: Using a Variable's value in Another Variables Name?](http://stackoverflow.com/questions/3346178), [Matlab- How does you name a new variable based on other variables' values?](http://stackoverflow.com/questions/3884752) – gnovice May 11 '11 at 17:37

2 Answers2

1

Do you want something like

eval( sprintf( 'info_%s = strcat( S.info1, S.info2 );', x{i} ) );

?

If so, could I discourage you from doing so, see: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

Edric
  • 23,676
  • 2
  • 38
  • 40
  • great man, that is exactly what I was looking for. However, I don't see why I shouldn't do it this way. – Mike May 11 '11 at 13:18
  • so now there seems only one problem left. After using the above command I receive 50 elements, which I would now like to put into one dataset array. I checked out the help for dataset() but couldn't figure it out. If there is no way to address the 50 elements concretely it would suffice if I could just put all my workspace elements into the dataset but I couldn't find an option for that either. – Mike May 11 '11 at 14:49
0

Try the following:

eval(['info_x{' num2str(i) '}=strcat(S.info1, S.info2)']);
peakxu
  • 6,667
  • 1
  • 28
  • 27
  • thanks for helping but this unfortunately doesn't work. You should know that x{i} returns a string. Basically I want to name each element 1:50 by this respective string. – Mike May 11 '11 at 13:03