0

Let's say I've a cell array of string:

A = {'hello','world','how','are','you'};

I want to add the letter z at the end of every string, in order to obtain:

Az = {'helloz','worldz','howz','arez','youz'};

I'm using a for loop to accomplish this task, however I would like to improve it as much as possible.

This is the code I'm currently using:

Az = cell(size(A)); % Preload
for i = 1:size(A,2)
    Az{i} = [A{i},'z'];
end

Any suggestion?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
mat
  • 2,412
  • 5
  • 31
  • 69
  • If you want to improve the loop I suggest [not using `i` as a variable](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab), to eliminate the loop entirely, try [`cellfun`](http://mathworks.com/help/matlab/ref/cellfun.html) – Adriaan Oct 14 '15 at 16:51

1 Answers1

4

strcat does just that:

Az = strcat(A, 'z');

From the documentation,

s = strcat(s1,...,sN) horizontally concatenates strings s1,...,sN. Each input argument can be a single string, a collection of strings in a cell array, or a collection of strings in a character array.

If any input argument is a cell array, the result is a cell array of strings. Otherwise, the result is a character array.

For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form feed. For cell array inputs, strcat does not remove trailing white space.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147