Given a vector containing a certain number of elements, for example vector=[2,4,3], I have to create a vector containing in each row (or column) the name of the corresponding planet in the solar system. In the case of the previous vector, the result should be PlanetName=['Venus';'Mars';'Earth']. Can you suggest me a method to create such a vector? thank you.

 채택된 답변

Jan
Jan 2015년 12월 27일
편집: Jan 2015년 12월 27일

0 개 추천

There are no "string vectors" in Matlab, but you need a "cell string":
Planets = {'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'}
Index = [2, 4, 3];
Chosen = Planets(Index)
See the "Getting Started" chapters of the documentation, because such a powerful tool as Matlab demands for learning the basics from the documentation.
EDITED: And when you really have a good reason not to use a cell string, but a char-matrix:
Chosen = char(Planets(Index))
Now the strings are padded with zeros. But it is less useful to work with char matrices. Prefer cell strings whenever it is possible.

댓글 수: 5

Andre Ged
Andre Ged 2015년 12월 27일
Sorry, I forgot to specify that the output has to be of this type: char, instead of cell.
Jan
Jan 2015년 12월 27일
This is not possible in Matlab, because the strings have a different number of characters. The thing, which is near to a "string vector" is a CHAR-matrix, but then you have to pad teh shorter names with zeros. See EDITED.
Andre Ged
Andre Ged 2015년 12월 27일
Thank you
Walter Roberson
Walter Roberson 2015년 12월 27일
Actually the padding is with blanks when you use char() on a cell array of strings.
Jan
Jan 2015년 12월 29일
@Walter: I still try to ignore, that Matlab pads CHAR matrices with blanks, because zeros are less intrusive.

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 12월 27일

0 개 추천

You can use cell arrays, for example:
planet={'planet1' 'planet2' 'planet3' 'planet4'}
vector=[2,4,3]
our=planet(vector)

카테고리

도움말 센터File Exchange에서 Earth and Planetary Science에 대해 자세히 알아보기

태그

질문:

2015년 12월 27일

댓글:

Jan
2015년 12월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by