在MATLAB中,如何在单元格数组中每个字符串的开头插入一个字符串? [英] In MATLAB how do I insert a string at beginning of of each string in a cell array?

查看:743
本文介绍了在MATLAB中,如何在单元格数组中每个字符串的开头插入一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字字符串的单元格数组,例如:

I have a cell array of numeric strings e.g.:

labels = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'}

我试图在每个数组元素的开头添加一个字符串('Label '),而不使用任何类型的循环,因为数组很大,我需要代码快速运行.我的另一个要求是,一旦将'Label'应用于数组中的两位数元素,就必须保留该空格.我想要的结果是:

I'm trying to add a string ('Label ') to the beginning of each array element without using any kind of loop, as the array is massive and I need the code to run quickly. My other requirement is the space after the word 'Label' must be maintained once I apply it to the two-digit elements in the array. The result I want is:

fullLabels = {'Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5',
              'Label 6', 'Label 7', 'Label 8', 'Label 9', 'Label 10',
              'Label 11', 'Label 12'}

我尝试像这样使用 strcat() :

I tried using strcat() like this:

fullLabels = strcat('Label ', labels);

这对于一位数字数组元素来说很好,但是当将其应用于两位数数组元素时,'Label'之后的空格将被删除以给出:

This is fine for the single-digit array elements, but when it is applied to the two-digit array elements, the space after 'Label' is removed to give:

fullLabels = {..., 'Label10', 'Label11', 'Label12'}

推荐答案

strcat在串联之前从所有输入中修剪尾随空格.您将要使用[]手动连接字符串.

strcat trims trailing whitespace from all inputs prior to concatenation. You will want to manually concatenate the strings using [].

fullLabels = cellfun(@(x)['Label ', x], labels, 'UniformOutput', false)

%   'Label 1'
%   'Label 2'
%   'Label 3'
%   'Label 4'
%   'Label 5'
%   'Label 6'
%   'Label 7'
%   'Label 8'
%   'Label 9'
%   'Label 10'
%   'Label 11'
%   'Label 12'

您也可以使用regexprep之类的标签作为前缀.这样会将每个标签的第一个字符(\1)替换为前面的'Label '.

You could also use something like regexprep to prepend the label. This replaces the first character of each label with itself (\1) with 'Label ' appended to the front.

fullLabels = regexprep(labels, '^.', 'Label \1')

更新

@ Dev-iL的答案是使用单元格数组将空间传递给我不知道的strcat.除了连接空间之外,我们还可以将'Label ' 插入到单元格中.

@Dev-iL's answer mentioned using a cell array to pass a space to strcat which I wasn't aware of. Rather than concatenating the space, we could also just stick 'Label ' inside the cell.

strcat({'Label '}, labels)

这篇关于在MATLAB中,如何在单元格数组中每个字符串的开头插入一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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