3

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?

MatlabDoug
  • 5,704
  • 1
  • 24
  • 36
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

2 Answers2

3

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

params = strcat({'-a '},int2str(a(:)),{' -b '},int2str(b(:)));
gnovice
  • 125,304
  • 15
  • 256
  • 359
2

A slightly simpler solution:

strcat(num2str([a(:) b(:)],'-a %d -b %d'), {})
Amro
  • 123,847
  • 25
  • 243
  • 454
  • 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 Mar 02 '10 at 22:34
  • 2
    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 Mar 02 '10 at 22:46
  • 2
    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 Mar 02 '10 at 22:57
  • 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 Mar 02 '10 at 23:45