char vector

조회 수: 49 (최근 30일)
Danielle Leblanc
Danielle Leblanc 2011년 10월 15일
Hi,
I am trying to build a variable x . I want it ti be a 3 by 1 vector where row1 is y, row2 is v1 and row3 is v2. I tried : x=['y';'v1';'v2'] but I am receiving an error. I tried other methods without success

답변 (1개)

Walter Roberson
Walter Roberson 2011년 10월 15일
Probably the easiest way to do that is
char({'y';'v1';'v2'})
However, if the longest string had trailing blanks, some of those blanks may be lost.
In MATLAB, there is no independent string data type. A string is a character row vector. Your request for a 3 by 1 vector is thus a request for a column vector that is exactly 1 character wide. You are requesting to put 5 characters in to something you want to have only 3 total characters.
The most direct method to build the character array is to pad each row out with blanks so that all the rows are the same size:
x = ['y ';'v1';'v2'];
This would create a 3 x 2 character array. x(2,:) would be 'v1' -- but x(1,:) would be 'y ' (y space). If you want to use variable-length strings then you need to use a cell array such as
x = {'y';'v1';'v2'};
With that, x{1} would be 'y', x{2} would be 'v1'. Notice the use of {} to get to the contents. x(1) would be {'y'} which is a cell array that has a single member that contains 'y'.
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 10월 15일
Note that
char({y;v1;v2})
will produce a character array of the proper width to include the contents of each of the variables, but lines will be padded with blanks to become equal to the length of the longest line.
{y;v1;v2}
will produce a cell array that can be indexed as described above, with {} .

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by