如何连接字符串 +我?
for i=1:N
f(i) = 'f'+i;
end
在 MatLab 中给出错误。使用模式 fi 的 N 个字符串初始化数组的正确语法是什么?
似乎这也不起作用:
for i=1:4
f(i) = 'f';
end
for i=1:N
f(i) = 'f'+i;
end
gives an error in MatLab. What's the correct syntax to initialize an array with N strings of the pattern fi?
It seems like even this is not working:
for i=1:4
f(i) = 'f';
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
strcat
连接字符串。如果您计划将数字连接为字符串,则必须首先使用num2str
将数字转换为字符串。
此外,字符串不能存储在向量或矩阵中,因此
f
必须定义为 元胞数组,并且必须使用{
和}
(而不是普通的圆括号)进行索引。You can concatenate strings using
strcat
. If you plan on concatenating numbers as strings, you must first usenum2str
to convert the numbers to strings.Also, strings can't be stored in a vector or matrix, so
f
must be defined as a cell array, and must be indexed using{
and}
(instead of normal round brackets).对于 R2014a 之前的版本...
一种简单的非循环方法是使用
genvarname
创建一个 单元格字符串数组:对于较新的版本...
函数
genvarname
已被弃用,因此matlab.lang.makeUniqueStrings
可以按以下方式使用以获得相同的输出:For versions prior to R2014a...
One easy non-loop approach would be to use
genvarname
to create a cell array of strings:For newer versions...
The function
genvarname
has been deprecated, somatlab.lang.makeUniqueStrings
can be used instead in the following way to get the same output:让我添加另一个解决方案:
如果
N
长度超过两位数 (>= 10
),您将开始获得额外的空格。添加对strtrim(f)
的调用来消除它们。作为奖励,有一个未记录的内置函数 sprintfc 可以很好地返回字符串元胞数组:
Let me add another solution:
If
N
is more than two digits long (>= 10
), you will start getting extra spaces. Add a call tostrtrim(f)
to get rid of them.As a bonus, there is an undocumented built-in function
sprintfc
which nicely returns a cell arrays of strings:ldueck 在评论中已经提出使用 sprintf ,但我认为这值得作为一个答案:
在我看来,这是最具可读性的解决方案,并且还提供了一些很好的灵活性(即,当您想要舍入时)浮点值,使用类似
%.2f
的值)。Using
sprintf
was already proposed by ldueck in a comment, but I think this is worth being an answer:This is in my opinion the most readable solution and also gives some nice flexibility (i.e. when you want to round a float value, use something like
%.2f
).根据 this 看起来你必须在尝试之前设置“N”要使用它,看起来它需要是一个 int 而不是字符串?对 MatLab 不太了解,但只是我从该网站收集的信息..希望它有帮助:)
according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)
尝试以下操作:
如果您使用它来命名代码生成的多个文件,您可以将更多部分连接到该名称。例如,扩展名位于末尾,地址位于开头:
Try the following:
If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning: