Qiang Li
Qiang Li

Reputation: 10855

matlab: given a prefix string, how to generate a sequence

For example, the prefix string is 'fig', I want to have a new string with the sequence 'fig1,fig2,fig3,...,fig100', how to do this conveniently without using a for loop? Many thanks!

Upvotes: 1

Views: 553

Answers (1)

Jonas
Jonas

Reputation: 74940

I assume you want a cell array of strings, i.e. {'fig1','fig2',...'}

Here's one of many ways to achieve this (change the format string to 'fig%03i' if you want the output to be 'fig001','fig002' etc):

figString = arrayfun(@(x)sprintf('fig%i',x),1:100,'uniformOutput',false)

EDIT

If you only want a single string, i.e. 'fig1,fig2, ...', the easiest solution is to use sprintf:

figString = sprintf('fig%i,',1:100);
figString = figString(1:end-1); %# remove the comma at the end

Upvotes: 2

Related Questions