Preallocate char array: Wrong values

20 ビュー (過去 30 日間)
Nycholas Maia
Nycholas Maia 2019 年 1 月 9 日
コメント済み: Nycholas Maia 2019 年 1 月 10 日
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?

採用された回答

dpb
dpb 2019 年 1 月 9 日
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 件のコメント
Nycholas Maia
Nycholas Maia 2019 年 1 月 10 日
you are completelly right dpb!
thank you for your quick answer!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by