MATLAB Answers

Using strings in regular code.

Asked by Clifford Shelton on 5 Jul 2012
Accepted Answer by F.

Simple question. I've looked around the documentation and can't seem to find this.

How do I use a string and pass it into code?? Example:

%I create a string
Str = Superman

then how do I pass this string in the saveas command? So instead of writing this line of code:


I would write something to the effect of:

saveas(gcf,''Str'.fig') or something?!?!??!?!?




No products are associated with this question.

1 Answer

Answer by F.
on 5 Jul 2012
 Accepted answer

For me, to construct the name of the file (it's what I use)

   FileName = 'Superman' ;
   FileDir = 'I:\..\MyDir'
   FilePath = fullfile( FileDir, sprintf( '%s.fig', FileName ));

You can write this in one line if you want


John Petersen
on 5 Jul 2012

F. gave you a very complete answer, but more than you wanted or could understand. Maybe this is all you want:

Str = 'Superman'; 
saveas(gcf,[Str '.fig']);
on 5 Jul 2012

You could also try

Str = 'Superman'
Kevin Claytor
on 5 Jul 2012

Strings are indicated by single quotes; ''

You can concatenate strings with either the strcat(s1,s2,...) command or the straight brakets; [].

So the code would look like;

str1 = 'superman'
str2 = '.fig'
comb1 = strcat(str1,str2)
comb2 = [str1, str2]

The output of both gives you "superman.fig". To use in a call to another function you can just use one of the combined strings;


Or if you wanted to save some clutter, as those above did;


Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!