How to change the name of variables using a loop?
    44 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Kathleen
 el 25 de Sept. de 2014
  
I need to do the same matrix calculations repeatedly, but I want to rename the variable within the loop. e.g. I need matrices R_1 R_2 R_3 R_4. I want to be able to set matrix R_1=( calcs for ii=1); R_2=( calcs for ii=2), etc. I know I can convert ii to a string using num2str(ii), but how do I concatenate that to R? R_ii=(calcs for ii)?
Am I going to need some sort of cell array to do that? I'm trying to avoid cells.
3 comentarios
Respuesta aceptada
Más respuestas (2)
  Iain
      
 el 25 de Sept. de 2014
        Cells ARE the way to go.
Structures would be preferable to what you want
 mystruct.description = 'blah blah';
 mystruct = setfield(mystruct,['R_' num2str(ii) ], values);
However, sometimes, in rare cases, not using a monolithic storage solution is the only practical option. This option should be avoided whenever possible.
 eval(['R_' num2str(ii) ' = values;']);
0 comentarios
  Titus Edelhofer
    
 el 25 de Sept. de 2014
        Hi Kathleen,
why do you want to avoid cells? They are a perfect fit - and much cleaner/safer/easier to use than any clumsy and error prone variable creation based on names and indices ...?
Titus
0 comentarios
Ver también
Categorías
				Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!