Create a Matrix with multiple repeated strings

143 次查看(过去 30 天)
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]

采纳的回答

Walter Roberson
Walter Roberson 2017-5-27
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 个评论
Darcy Cordell
Darcy Cordell 2022-5-24
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
Stephen23 2022-5-24
编辑:Stephen23 2022-5-24
"If I have a string 'dog'"
'dog' is not a string, it is a character vector.
v = ['dog', 'dog', 'dog', 'dog']
v = 'dogdogdogdog'
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'
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"]
v = 1×4 string array
"dog" "dog" "dog" "dog"

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by