How do I prevent MATLAB from converting characters into their ASCII equivalent?
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (3)
Voss
el 28 de Sept. de 2022
number = 7;
char_vector = repmat('*',1,number);
disp(char_vector);
0 comentarios
David Hill
el 28 de Sept. de 2022
Editada: David Hill
el 28 de Sept. de 2022
A=repmat('*',1,10)
A=repelem('*',10)
0 comentarios
Walter Roberson
el 28 de Sept. de 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
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 comentarios
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!