I have written a code that generates 20 strings (the number actually varies depending on the input), all of which have the names "s_idx_?" where ? is a number from 1 to 20. Is there a command that allows me to concatenate all these strings without having to type out all the names? Thanks.

5 comentarios

Nathan Greco
Nathan Greco el 19 de Jul. de 2011
First: it is generally nicer to create one data structure to contain all of these strings rather than creating a variable per string. Look up cell arrays, they are your friend. Rather than calling your strings s_idx_?, you could just call them s{?} where ? is your old number.
E. Elgar
E. Elgar el 19 de Jul. de 2011
Actually I'm oversimplifying the problem a bit. This is the code I have:
for e = 1:length(c)
f = eval(c{e}); % for each c, f gives the list of cues under the condition
for g = 1:length(f) % runs through the whole string of cues (f)
i = f{g};
h = genvarname('s_idx_',who);
eval([h '= find(strcmp(''' i ''',theData.study.cue))']); % matches each i with a number from some list I have
end
end
The output is a bunch of variables called "s_idx_?". The number of variables will change if I change the input. I've tried creating cell arrays as Nathan suggested, but it doesn't seem to work.
Sean de Wolski
Sean de Wolski el 19 de Jul. de 2011
POISON!! EVAL!! Don't do it!!
E. Elgar
E. Elgar el 20 de Jul. de 2011
!! Other solutions then?

Iniciar sesión para comentar.

 Respuesta aceptada

Sean de Wolski
Sean de Wolski el 19 de Jul. de 2011

1 voto

Don't do it!
but if you have to:
sprintf('s_idx_%i\n',1:20)

1 comentario

Jan
Jan el 20 de Jul. de 2011
I agree with "Don't do it". The SPRINTF command concatenates the _names_ of the variables?! The OP wants to cat the string values.

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 20 de Jul. de 2011

2 votos

Follow Sean's link to the FAQ. There you find the suggestion to use a cell like "s_idx{i}" instead of including the index in the name of the variables. Thjen the concatenation is easy:
s = cat(2, s_idx{:});

1 comentario

E. Elgar
E. Elgar el 20 de Jul. de 2011
Thank you! I think this will work.

Iniciar sesión para comentar.

Categorías

Más información sobre Variables en Centro de ayuda y File Exchange.

Preguntada:

el 19 de Jul. de 2011

Editada:

el 12 de Sept. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by