Create a Matrix with multiple repeated strings
135 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Panos Ale
el 26 de Mayo de 2017
I have str1='a' str2='b' str3='c' and I want to create a matrix F=[ str1..3 times str2..6 times str3 12 times]
0 comentarios
Respuesta aceptada
Walter Roberson
el 27 de Mayo de 2017
F = [repmat(str1, 1, 3), repmat(str2, 1, 6), repmat(str3, 1, 12)];
In the special case where your items are all only single characters,
F = repelem([str1, str2, str3], [3 6 12]);
Both of these would produce 'aaabbbbbbcccccccccccc' .
But possibly you want
F = [repmat({str1}, 1, 3), repmat({str2}, 1, 6), repmat({str3}, 1, 12)];
or
F = repelem([{str1}, {str2}, {str3}], [3 6 12])'
if your desired answer is
'a' 'a' 'a' 'b' 'b' 'b' 'b' 'b' 'b' 'c' 'c' 'c' 'c' 'c' 'c' 'c' 'c' 'c' 'c' 'c' 'c'
If you have R2016b or R2017a and have constructed your items as string objects, like (R2017a or later)
str1 = "a"; str2 = "b"; str3 = "c";
then you can use
F = repelem([str1, str2, str3], [3 6 12]);
if your desired output is
"a" "a" "a" "b" "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c" "c"
and you can use
F = strjoin( repelem([str1, str2, str3], [3 6 12]), '' );
if your desired output is "aaabbbbbbcccccccccccc"
3 comentarios
Darcy Cordell
el 24 de Mayo de 2022
Thanks for the detailed answer. However, as far as I can tell, none of your solutions solve my specific problem.
If I have a string 'dog', I want to repeat it so that it is like this:
v = ['dog', 'dog', 'dog', 'dog']
Each string is a separate entry in the vector v. All of your solutions seem to either put the string into cells (e.g. [{'dog'}, {'dog'}, {'dog'}]) or concatenate all the strings together (e.g. ['dogdogdogdogdog']).
Any help is appreciated.
Stephen23
el 24 de Mayo de 2022
Editada: Stephen23
el 24 de Mayo de 2022
"If I have a string 'dog'"
'dog' is not a string, it is a character vector.
v = ['dog', 'dog', 'dog', 'dog']
In MATLAB square brackets are a concatenation operator (not a "list" operator, which MATLAB does not have, the closest thing is perhaps a cell array), so your example is exactly equivalent to this:
v = 'dogdogdogdog'
"Each string is a separate entry in the vector v."
What you showed is just one character vector (every element of which is one character).
"Any help is appreciated."
Probably you should be using string arrays:
v = ["dog", "dog", "dog", "dog"]
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrices and Arrays 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!