在matlab中将单元格与分隔符连接起来

时间:2021-10-21 15:57:30

This should be very simple. I have a cell array with two columns. One is numbers, and the other is colors. I want to concatenate these two columns into a single column separated by underscores. For example, I have something like this:

这应该很简单。我有一个有两列的单元格数组。一个是数字,另一个是颜色。我想将这两列连接成一个由下划线分隔的列。例如,我有这样的事情:

plant_tag = {3,'dark_blue';3,'dark_blue';3,'dark_blue'}

and I want something like this:

我想要这样的东西:

desired = {'3_dark_blue'; '3_dark_blue'; '3_dark_blue'}

I've looked here and other places How can I concatenate strings in a cell array with spaces between them in MATLAB?

我看过这里和其他地方如何在MATLAB中连接单元格数组中的字符串和它们之间的空格?

Here's what I've tried so far

这是我到目前为止所尝试的内容

% Gives me errors
test2 = strjoin(plant_tag,'_');
test3 = strjoin(plant_tag(1,:),'_');
test4 = strjoin(cellstr(plant_tag(1,:)),'_');
test5 = strjoin(cellstr(plant_tag{1,:}),'_');

% No error, but misses number
test6 = [plant_tag{1,1} plant_tag{1,2}];
test7 = [plant_tag{1,:}];

I'm sure I'm missing something here--I apologize if it is something obvious

我确定我在这里遗漏了一些东西 - 如果有明显的东西,我道歉

3 个解决方案

#1


Here's a vectorized solution:

这是一个矢量化解决方案:

desired = strcat(num2str([plant_tag{:,1}].'), '_', plant_tag(:,2));

#2


You can accomplish this using strcat (and also converting the 3 doubles to a string):

您可以使用strcat完成此操作(并将3个双精度转换为字符串):

>> strcat( cellfun(@(c)num2str(c),plant_tag(:,1)) , '_' , plant_tag(:,2))

ans = 
    '3_dark_blue'
    '3_dark_blue'
    '3_dark_blue'

#3


With a good-old for loop:

有一个很好的for循环:

clear
clc

plant_tag = {3,'dark_blue';2,'dark_red';1,'dark_green'}

desired = cell(size(plant_tag,1),1);
for k = 1:size(plant_tag,1)

   desired{k} = strcat(num2str(plant_tag{k,1}),'_',plant_tag{k,2});

end
desired

Output:

desired = 

    '3_dark_blue'
    '2_dark_red'
    '1_dark_green'

#1


Here's a vectorized solution:

这是一个矢量化解决方案:

desired = strcat(num2str([plant_tag{:,1}].'), '_', plant_tag(:,2));

#2


You can accomplish this using strcat (and also converting the 3 doubles to a string):

您可以使用strcat完成此操作(并将3个双精度转换为字符串):

>> strcat( cellfun(@(c)num2str(c),plant_tag(:,1)) , '_' , plant_tag(:,2))

ans = 
    '3_dark_blue'
    '3_dark_blue'
    '3_dark_blue'

#3


With a good-old for loop:

有一个很好的for循环:

clear
clc

plant_tag = {3,'dark_blue';2,'dark_red';1,'dark_green'}

desired = cell(size(plant_tag,1),1);
for k = 1:size(plant_tag,1)

   desired{k} = strcat(num2str(plant_tag{k,1}),'_',plant_tag{k,2});

end
desired

Output:

desired = 

    '3_dark_blue'
    '2_dark_red'
    '1_dark_green'