Reputation: 483
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?
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
Upvotes: 1
Views: 873
Reputation: 112689
Here's a vectorized solution:
desired = strcat(num2str([plant_tag{:,1}].'), '_', plant_tag(:,2));
Upvotes: 3
Reputation: 13945
With a good-old for loop:
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'
Upvotes: 2
Reputation: 8401
You can accomplish this using strcat
(and also converting the 3
doubles to a string):
>> strcat( cellfun(@(c)num2str(c),plant_tag(:,1)) , '_' , plant_tag(:,2))
ans =
'3_dark_blue'
'3_dark_blue'
'3_dark_blue'
Upvotes: 2