Using strings in regular code.

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:
saveas(gcf,'Superman.fig');
I would write something to the effect of:
saveas(gcf,''Str'.fig') or something?!?!??!?!?
Thanks!

 채택된 답변

F.
F. 2012년 7월 5일

0 개 추천

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 ));
saveas(gcf,FilePath)
You can write this in one line if you want

댓글 수: 6

Clifford Shelton
Clifford Shelton 2012년 7월 5일
that's kinda cool. but would you know how to do what I want to by using the string?
Thanks!
F.
F. 2012년 7월 5일
I'm sorry but I don't understand your comment
Clifford Shelton
Clifford Shelton 2012년 7월 5일
Sorry for being so confusing. What I mean is I still don't know how to do what I originally wanted to do. How would I call the superman string that I created and pass it into the saveas code?
I want to basically learn how to pass strings into code in general.
Would you know how to do exactly what I asked in my original question? Thanks for your help!
John Petersen
John Petersen 2012년 7월 5일
편집: John Petersen 2012년 7월 5일
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']);
You could also try
Str = 'Superman'
filename=sprintf('%s.fig',Str)
saveas(gcf,filename)
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;
saveas(gcf,comb1)
Or if you wanted to save some clutter, as those above did;
saveas(gcf,[str1,'.fig'])

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by