如何将数字数组转换为字符的单元格数组,并在一行中与字符连接?
示例:
我有一个数字数组:
[1, 5, 12, 17]我想将它转换成一个由字符组成的单元格数组,并将其与字符“传感器”连接起来,并获得:
{'Sensor 1', 'Sensor 5', 'Sensor 12', 'Sensor 17'}有没有办法在一条线上做到这一点?
我现在得到的:
nums = [1, 5, 12, 17];
cellfun(@(x) ['Sensor ' num2str(x)], num2cell(nums), 'UniformOutput', 0)有没有一种更简单或更紧凑的方法?
发布于 2019-05-15 13:00:20
您可以使用sprintf()和arrayfun()使其变得更整洁,但不确定这会为您节省很多:
nums = [1, 5, 12, 17];
arrayfun(@(x) {sprintf('Sensor %d',x)}, nums) % Gives a cell array of char array strings
arrayfun(@(x) sprintf("Sensor %d",x), nums) % Gives an array of string strings (version 2016b onwards)从2016年a开始,你也可以在MATLAB的版本中使用compose():
compose('Sensor %d', nums) % Char array
compose("Sensor %d", nums) % String array (version 2017a onwards)发布于 2019-05-15 14:12:26
使用字符串的简单替代方法:
>> nums = [1, 5, 12, 17];
>> cellstr("Sensor " + nums)
ans =
1×4 cell array
{'Sensor 1'} {'Sensor 5'} {'Sensor 12'} {'Sensor 17'}字符串需要MATLAB R2017a。
发布于 2019-07-08 07:12:56
另一个只使用“在R2006a之前引入”函数的选项是:
A = [1, 5, 12, 17];
B = strcat('Sensor', {' '}, strtrim(cellstr(int2str(A.'))) );这会产生一个列向量,因此您应该根据需要进行转置。
https://stackoverflow.com/questions/56149522
复制相似问题