views:

52

answers:

2

I have a library function that takes parameters as a text string (it's a general C library with a MATLAB frontend). I want to call it with a set of parameters like this:

'-a 0 -b 1'
'-a 0 -b 2'
'-a 0 -b 3'
'-a 1 -b 1'
'-a 1 -b 2'
'-a 1 -b 3'

etc...

I'm creating the values of a and b with meshgrid:

[a,b] = meshgrid(0:5, 1:3);

which yields:

a =

 0     1     2     3     4     5
 0     1     2     3     4     5
 0     1     2     3     4     5

b =

 1     1     1     1     1     1
 2     2     2     2     2     2
 3     3     3     3     3     3

And now I want to somehow put these into a cell of strings:

params = {'-a 0 -b 1'; -a 0 -b 2'; etc...}

I tried using sprintf, but that only concatenates them

sprintf('-a %f -b %f', a ,b)

ans =

-a 0.000000 -b 0.000000-a 0.000000 -b 1.000000-a 1.000000 -b 1.000000-a 2.000000 -b 2.000000-a 2.000000 -b 3.000000-a 3.000000 -b 3.000000-a 4.000000 -b 4.000000-a 4.000000 -b 5.000000-a 5.000000 -b 5.000000-a 1.000000 -b 2.000000-a 3.000000 -b 1.000000-a 2.000000 -b 3.000000-a 1.000000 -b 2.000000-a 3.000000 -b 1.000000-a 2.000000 -b 3.000000-a 1.000000 -b 2.000000-a 3.000000 -b 1.000000-a 2.000000 -b 3.000000

Other than looping over a and b, how can I create the desired cell?

+3  A: 

You could try this, using the INT2STR and STRCAT functions:

params = strcat({'-a '},int2str(a(:)),{' -b '},int2str(b(:)));
gnovice
The accepted answer and upvote, sir, go to you!
Nathan Fellman
+1  A: 

A slightly simpler solution:

strcat(num2str([a(:) b(:)],'-a %d -b %d'), {})
Amro
I think NUM2STR will draw values from the matrix `[a(:) b(:)]` in column order, so you may have to transpose the matrix first. You could also use CELLSTR instead of STRCAT.
gnovice
are you sure about NUM2STR? take this simple test: `num2str([1 2; 3 4; 5 6],'%d\n')` or `num2str([1 2; 3 4; 5 6],'%d %d')` to match the above
Amro
This is different from FPRINTF/SPRINTF behavior, so I can see how one might think that.. (compare against `sprintf('%d\n',[1 2; 3 4; 5 6])`)
Amro
I think the confusion arose from the fact that the documentation for NUM2STR links to FPRINTF for a description of how the format part works. They should probably make that difference a little clearer.
gnovice