Wouter Kuijsters
Wouter Kuijsters

Reputation: 840

Using strcat to generate list of strings - how to include spaces?

I am trying to store variable and constraint names in a MATLAB struct. In order to do this, I tried the following:

JiSet = 1:6; nF = length(JiSet);
P.names.con(1:nF,1) = cellstr(strcat('x position for robot ',int2str(JiSet(:))));

Seems simple enough, right? Apparently not, because I get the following output:

'x position for robot1'
'x position for robot2'
'x position for robot3'
'x position for robot4'
'x position for robot5'
'x position for robot6'

I want a space to appear between the text robot and its corresponding number. Apparently strcat cuts trailing spaces, how do I make sure they are included? I also tried an approach of the form ['x position for robot ' int2str(JiSet(:))], but that doesn't work either since the int2str part is a vector so the dimensions don't match.

Upvotes: 1

Views: 97

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

Instead of using strcat you could do it using the undocumented function sprintfc (Check here for infos) that populates cell arrays with strings:

clear
clc

JiSet = 1:6; 
nF = length(JiSet);

P.names.con(1:nF,1) = sprintfc('x position for robot %i',JiSet);

Names = P.names.con;

%// You can combine this step with the former but I leave it like this for clarity purposes

Names = vertcat(Names)

Names = 
    'x position for robot 1'
    'x position for robot 2'
    'x position for robot 3'
    'x position for robot 4'
    'x position for robot 5'
    'x position for robot 6'

Upvotes: 4

Setsu
Setsu

Reputation: 1228

Make the first argument a cell.

JiSet = 1:6; nF = length(JiSet);
P.names.con(1:nF,1) = cellstr(strcat({'x position for robot '},int2str(JiSet(:))));

Gives the output:

>> P.names.con
ans = 
    'x position for robot 1'
    'x position for robot 2'
    'x position for robot 3'
    'x position for robot 4'
    'x position for robot 5'
    'x position for robot 6'

From the documentation:

For cell array inputs, strcat does not remove trailing white space.

Upvotes: 2

Related Questions