Create a Matrix with multiple repeated strings

527 views (last 30 days)
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]

Accepted Answer

Walter Roberson
Walter Roberson on 27 May 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 Comments
Darcy Cordell
Darcy Cordell on 24 May 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
Stephen23 on 24 May 2022
Edited: Stephen23 on 24 May 2022
"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"

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!