5

Given a single string value in a MATLAB character array:

['12 N']

How can I repeat this value X times in a new character array?

For example:

X = 5

['12 N'; '12 N'; '12 N'; '12 N'; '12 N']
Borealis
  • 8,044
  • 17
  • 64
  • 112

2 Answers2

10

Use the repmat function:

A = ['12 N'];
X = 5
Output = repmat(A, X, 1);

will result in a character array.

Depending on your end usage, you may want to consider using a cell array of strings instead:

Output = repmat({A},X,1);
Doresoom
  • 7,398
  • 14
  • 47
  • 61
DaveH
  • 534
  • 1
  • 7
  • 17
  • Ah, you beat me as I was typing out the answer! – Doresoom Mar 07 '14 at 18:58
  • The last line is incorrect: `repmat({A},X,1);` creates a cell array of char arrays, not strings. (Edit: I realize that when this answer was posted, Matlab had not introduced the `string` class yet, so the words "strings" were sometimes used to refer to char arrays) – Paul Wintz Sep 28 '21 at 22:36
3

repmat is the obvious way to go, but just for the heck of it you could use kron:

A = ['12 N'];
X = 5
B = char(kron(A,ones(X,1)))

Silly, yes...

chappjc
  • 30,359
  • 6
  • 75
  • 132