Clear Filters
Clear Filters

char vector

39 views (last 30 days)
Danielle Leblanc
Danielle Leblanc on 15 Oct 2011
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

Answers (1)

Walter Roberson
Walter Roberson on 15 Oct 2011
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 Comment
Walter Roberson
Walter Roberson on 15 Oct 2011
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 {} .

Sign in to comment.

Categories

Find more on Data Types in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!