How to concat string + i?

simpatico picture simpatico · Dec 7, 2011 · Viewed 181.6k times · Source
for i=1:N
   f(i) = 'f'+i;
end

gives an error in MatLab. What's the correct syntax to initialize an array with N strings of the pattern fi?

It seems like even this is not working:

for i=1:4
  f(i) = 'f';
end

Answer

Mansoor Siddiqui picture Mansoor Siddiqui · Dec 7, 2011

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));
end