필터 지우기
필터 지우기

Create string from a cell array

조회 수: 8 (최근 30일)
daniel.x16
daniel.x16 2011년 6월 10일
Hi,
I have a list of names in a 1 by n matrix. I would like to make them into one string (to generate file names, the end result of my program saves a graph to a file). The names are from varargin (which allows variable amount of inputs)
names=varargin;
I have tried using:
char(names)
This does give a character result, but over n rows. I want one string. Ideally, I would be able to seperate names with underscores, but I would settle for just a string (no spaces) of the names.
Any help would be great.
  댓글 수: 1
Andrew Newell
Andrew Newell 2011년 6월 10일
Don't forget to indent your code two spaces (see http://www.mathworks.com/matlabcentral/answers/7885-tutorial-how-to-format-your-question).

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

채택된 답변

Jan
Jan 2011년 6월 10일
Simple and fast:
Str = sprintf('%s_', varargin{:});
Str(end) = [];
But if the cell string has a lot of elements, this can be imrpoved: Obviously SPRINTF does not preallocate the complete string at first. Then try: FEX: CStr2String.
  댓글 수: 1
daniel.x16
daniel.x16 2011년 6월 10일
Perfect! Thanks so much!

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

추가 답변 (2개)

Walter Roberson
Walter Roberson 2011년 6월 10일
cell2mat(strcat(varargin,'_'))
You can then delete the trailing _ from that if you like.

Andrew Newell
Andrew Newell 2011년 6월 10일
If you want to be sure that there are no whitespace characters, you could use this:
regexprep([names{:}],'\s+','_')
e.g.,
names = {'Cup ',' a ','Joe'}
gives
Cup_a_Joe
Of course, you will get surprises if there is a blank in the middle of one of your arguments!

카테고리

Help CenterFile 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