How do I prevent MATLAB from converting characters into their ASCII equivalent?
11 views (last 30 days)
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
array = zeros(1,number);
array(array == 0) = '*';
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?
Walter Roberson on 28 Sep 2022
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
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.