在Matlab中预分配字符串大小
我非常清楚如何使用1、0和单元格命令预先分配矩阵大小,但是字符串呢?
I am very well aware on how to pre-allocate Matrix sizes using ones, zeros and cell command but what about a String ?
假设我有一个名为data
的矩阵,现在如果我想打印这些数字的ASCII字符而不是自己的数字,则每个值都在1-255之间,我会这样做,
Suppose I have a Matrix named data
whose each value is between 1-255 now if i want to print these number's ASCII characters instead of numbers it selves, I'd do that,
msg='';
for i = 1 : length(data)
msg=horzcat(msg,floor(data(i))); % horzcat doesn't ignore spaces
end
msg
在上面的代码中,
Matlab在循环结束之前并没有意识到msg
的大小,我真正想做的是在循环开始之前声明变量msg
的大小.
in the above code Matlab is unaware of the size of the msg
before the loop ends, What i really want to do is to declare the size of the variable msg
before the loop starts.
我该怎么做?
您可以像使用矩阵一样使用char
预分配字符串(字符串只是一个char数组):
You can use char
to preallocate a string just as you would a matrix (a string is just a char array):
msg = char(zeros(100,1));
但是,这可能不是您所需要的(我还没有看到任何人为任何东西预先分配一个字符串).既然这就是你想要做的
However, this is probably not what you need (I haven't seen anyone preallocate a string for anything). Given that this is what you want to do
假设我有一个名为data的矩阵,现在如果我想打印这些数字的ASCII字符而不是自己选择的数字,则每个值都在1-255之间
Suppose I have a Matrix named data whose each value is between 1-255 now if i want to print these number's ASCII characters instead of numbers it selves
您只需执行char(data)
即可显示ASCII/Unicode值.
you can simply do char(data)
to display the ASCII/Unicode values.