为什么将字符插入 MATLAB 矩阵时会出现此错误?
我正在构造一个 16x16 矩阵,仅由 MATLAB 中的字母组成。例如,我尝试
for i=1:2:3
C(i,2)=char('B');
end
将字母 'B'
放置在矩阵中相应的位置。但是,这会在矩阵中给出值 66
,而不仅仅是字母 'B'
。出了什么问题?
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:
for i=1:2:3
C(i,2)=char('B');
end
to place the letter 'B'
in its corresponding place in the matrix. However this gives a value of 66
in the matrix instead of just the letter 'B'
. What is going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题很可能是您已经有一个名为
C
的变量,其中包含数字数据。当您尝试将字符放入数字矩阵时,该字符会转换为其 ASCII 值。如果在运行上述代码之前清除变量C
,您应该获得C
的字符矩阵:请注意,在这种情况下,
C
是一个3×2 数组,第一列和第二列的第二行包含空字符(ASCII 代码0
)。如果要将C
初始化为由空字符组成的 16×16 字符数组,可以替换 CLEAR 语句在上面的代码中:然后运行循环来填充您的值。另请注意,
char('B')
是多余的,因为'B'
已经是字符类型。The problem is most likely that you already have a variable called
C
that contains numeric data in it. When you try to place a character into a numeric matrix, the character gets converted to its ASCII value. If you clear the variableC
before running your above code, you should get a character matrix forC
:Note in this case that
C
is a 3-by-2 array with null characters (ASCII code0
) in the first column and second row of the second column. If you want to initializeC
to be a 16-by-16 character array of null characters, you can replace the CLEAR statement in the above code with:And then run your loop to fill in your values. Also note that
char('B')
is redundant, since'B'
is already of type character.Matlab 将字母“B”存储为整数 ASCII 代码。实际上,char 表示 int8。
Matlab stores the letter 'B' as integer ASCII code. Ini fact, char means int8.
如果我这样做,
我会得到
C=AAA
,如您所料。我怀疑您获得 char 的十进制值的原因是您可能已将C
预先分配为C=zeros(16)
。 MATLAB 将数组初始化为numeric
类型,因此,当您用char
替换元素时,它会立即将其转换为其数值。更好的方法是使用单元格,然后将其转换为矩阵。
现在使用 cell2mat 将其转换为矩阵:
通常,我不会使用循环,但我不知道您的确切要求,所以我根据您的问题展示了一个示例。
If I do
I get
C=AAA
, as you'd expect. I suspect the reason why you're getting the decimal value of the char is because you might have preallocatedC
asC=zeros(16)
. MATLAB initialized the array asnumeric
type and accordingly, when you replaced an element with achar
, it promptly converted it to its numeric value.A better approach would be to use
cells
and then convert it to a matrix.Now use
cell2mat
to convert it to a matrix:Normally, I wouldn't use loops, but I don't know your exact requirements, so I've shown an example as per your question.