How do I prevent MATLAB from converting characters into their ASCII equivalent?
9 次查看(过去 30 天)
显示 更早的评论
I am currently trying to create a program that takes a number from 1 to 30, and prints a line that consists of that many asterisks. For instance, if I input "7", then the program will output "*******". So far, I have
function numbersToAsterisks(number)
array = zeros(1,number);
array(array == 0) = '*';
end
What I'm trying to do is to make a 1xn array that only consists of zeroes, and then replace all of those zeroes with asterisks. However, there are 2 problems:
- MATLAB keeps converting the asterisk into ASCII equivalent( * = 42)
- I don't know how to make it into a single line without spaces.
Is this the correct approach or should I do something entirely different?
0 个评论
回答(3 个)
Walter Roberson
2022-9-28
zeros() creates a numeric array, with a default data type of double()
Any time you assign a char() into a numeric array, MATLAB takes the Unicode code point (a non-negative integer) and assigns it into the array (after any appropriate datatype conversion). It does not convert to ASCII characters. ASCII is an 8-bit code with several regional variations, with only the first 128 values defined. MATLAB does not, for example, convert ö to o" or to oe:
ch = 'ö'
A = zeros(1,1)
A(1) = ch
char(246)
Notice the value is greater than 127, so this cannot possibly be an ASCII character.
It is not possible to prevent MATLAB from converting characters to numeric form when storing the characters into a numeric array. The internal difference between a uint16 array and a character array is that the character array has a value set in the header saying "this is char" and any output routines know that means that the 16 bit number is to be looked up in the font table for presentation purposes.
So... you should either initialize your array as character, such as by using blanks(), or else you should char() the numeric array for display purposes.
Reminder: binary zeros do not convert to whitespace on output as characters.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!