# How do I prevent MATLAB from converting characters into their ASCII equivalent?

14 ビュー (過去 30 日間)
Steven Deng 2022 年 9 月 28 日

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:
1. MATLAB keeps converting the asterisk into ASCII equivalent( * = 42)
2. 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?

サインインしてコメントする。

### 回答 (3 件)

Voss 2022 年 9 月 28 日
number = 7;
char_vector = repmat('*',1,number);
disp(char_vector);
*******
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

David Hill 2022 年 9 月 28 日

A=repmat('*',1,10)
A = '**********'
A=repelem('*',10)
A = '**********'
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

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 = 'ö'
ch = 'ö'
A = zeros(1,1)
A = 0
A(1) = ch
A = 246
char(246)
ans = 'ö'
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.

サインインしてコメントする。

### カテゴリ

Find more on Tables in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by