Create a Matrix with multiple repeated strings

129 Ansichten (letzte 30 Tage)
Panos Ale
Panos Ale am 26 Mai 2017
Bearbeitet: Stephen23 am 24 Mai 2022
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]

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 27 Mai 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 Kommentare
Darcy Cordell
Darcy Cordell am 24 Mai 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 am 24 Mai 2022
Bearbeitet: Stephen23 am 24 Mai 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"

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by