在Matlab中预分配字符串大小 [英] Pre-allocating the String size in Matlab

查看:95
本文介绍了在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.

这篇关于在Matlab中预分配字符串大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆