Preallocate char array: Wrong values
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nycholas Maia
el 9 de En. de 2019
Comentada: Nycholas Maia
el 10 de En. de 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?
0 comentarios
Respuesta aceptada
dpb
el 9 de En. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!