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]
0 个评论
采纳的回答
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
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
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']
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"]
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!