Preallocate char array: Wrong values

14 vues (au cours des 30 derniers jours)
Nycholas Maia
Nycholas Maia le 9 Jan 2019
Commenté : Nycholas Maia le 10 Jan 2019
I would like to preallocate a char array, fill it with data and then add this array to a table column.
The problem is that: each array field can be 2 or 3 chars, like: 'C4' and 'C#4'.
% Preallocate:
a = char(zeros(2, 1));
% Just a example, my in real-life this array will be field dynamically:
a = {'C4', 'C#4'};
myTable = table(a);
resut:
| a |
| 'C4£' |
| 'C#4' |
If I preallocate this array with 3 chars per filed, when I fill only 2 chars, the 3th char is showing a wrong / randow symbol.
To resolve this, now I using a string array....but I would like to do it this a char array...
Is this possible?

Réponse acceptée

dpb
dpb le 9 Jan 2019
Any array must be rectangular; char() arrays are no different. The array must be as wide (have as many columns) as the longest char() string you wish it to hold and all rows must be padded to that length if they are shorter than the maximum length. You can either pre- or postpend blanks, but you can't not fill all the space with something. If you try to fool mother Matlab, you'll either get a linear string if it can interpret the comand to do so or perhaps what appears as "gibberish" if you try to place values outside the range of printing ASCII characters into a char() array as you've done above.
That's why there are cellstr() and/or strings to handle variable length strings as entities, not as just arrays of bytes of type char.
What is the end result to be made of this variable in the resulting table and why do you think a char() representation is "more better" than string() or cellstr()? Frankly, it looks like perhaps a categorical variable might be more suitable than either, but don't know the objective so can't say for certain lacking additional input.
  1 commentaire
Nycholas Maia
Nycholas Maia le 10 Jan 2019
you are completelly right dpb!
thank you for your quick answer!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by