char vector
53 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Walter Roberson
le 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 commentaire
Walter Roberson
le 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 {} .
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!