char vector
49 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!