Preallocate char array: Wrong values

조회 수: 26 (최근 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 CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by