How to create variables using strings in an array?

4 visualizaciones (últimos 30 días)
J. Hu
J. Hu el 15 de Sept. de 2013
str1={'x','trs','height','width'}
str2='db_xtr'
For example, I wanted to do:
for ivar=1:size(str1,2)
C_%str1%_%str2%=ivar^2+2
end
to get following variables:
C_x_db_xtr = 1^2+2
C_trs_db_xtr = 2^2+2
C_height_db_xtr = 3^2+2
C_width_db_xtr = 4^2+2
seems function "genvarname" would do something similar but do not know how to do it for my particular case.
Thanks...

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 15 de Sept. de 2013
  1 comentario
J. Hu
J. Hu el 15 de Sept. de 2013
Editada: Azzi Abdelmalek el 29 de Sept. de 2013
It works. Great. Thanks... Seems the main reason not being recommended is that it runs slowly.
str1={'x','trs','height','width'}
str2='db_xtr'
for ivar=1:size(str1,2)
eval(sprintf('C_%s_%s=%d^2+2',str1{ivar},str2,ivar))
end

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 15 de Sept. de 2013
str1={'x','trs','height','width'}
str2='db_xtr'
input1 = [strcat(str1,'_',str2);num2cell((1:numel(str1)).^2+2)]
C = struct(input1{:})
  2 comentarios
J. Hu
J. Hu el 15 de Sept. de 2013
Thanks... however this is not exactly the way I want. It may work for some case. But how about if I need to put this in a multiple level loops and so the variable would be a 1D vector, 2D matrix like C_%str1%_%str2%(ivar1,ivar2)=ivar1^2+ivar2+2.
Walter Roberson
Walter Roberson el 15 de Sept. de 2013
Don't do that.
C{ivar1}{ivar2} = ... some matrix expression ...

Iniciar sesión para comentar.

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by