Preallocate char array: Wrong values

20 Ansichten (letzte 30 Tage)
Nycholas Maia
Nycholas Maia am 9 Jan. 2019
Kommentiert: Nycholas Maia am 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?

Akzeptierte Antwort

dpb
dpb am 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 Kommentar
Nycholas Maia
Nycholas Maia am 10 Jan. 2019
you are completelly right dpb!
thank you for your quick answer!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by