What exactly does char mean?

조회 수: 4 (최근 30일)
Changyu Liu
Changyu Liu 2020년 2월 20일
답변: Walter Roberson 2020년 2월 20일
>> answer = input('Enter YES or NO:\n','s');
fprintf('%c\n',answer)
Enter YES or NO:
YES
Y
E
S
>> answer = input('Enter YES or NO:\n','s');
fprintf('%s\n',answer)
Enter YES or NO:
YES
YES
>> E=char(i,answer)
E =
2×13 char array
'dsfdsfdsfdsfd'
'YES '
As you may notice, the first command suggests that char prints out the word character by character; however, the third command suggests that the char function simply puts out each string. Since both original data before conversion are strings, how is the result so different?

답변 (1개)

Walter Roberson
Walter Roberson 2020년 2월 20일
No, the first one you are using a %c format specifier. That does not directly have to do with the function named char(). The %c format specifier says that the next available output element is to be converted from numeric to the corresponding Unicode character and emitted. fprintf repeats the format as many times as needed to use up all of the output, so in this kind of call, each of the values would be converted one by one to character and those emitted. When this is done, each character in a character vector is treated as a different array element.
When %s is used as a format specifier, the complete rest of the current output argument is converted to characters, going down the columns in linear index order. It is possible that part of the output argument has already been converted; MATLAB just keeps going. All of it is treated as one row. Again this has nothing direct to do with the char function.
The char function converts input values to char.
For any one input that is numeric or character, the char output is the same shape, so a row vector of numeric values gets converted to a row vector of characters the same length.
char() has the additional property of acting like vertcat in stacking the representation of additional arguments vertically on top of each other, except that in each case it pads out shorter columns with blanks. The result is a char array, some entries of which may have blanks on the right hand side as needed to make a rectangular array.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by