问题
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?
回答1:
You could try this, using the INT2STR and STRCAT functions:
params = strcat({'-a '},int2str(a(:)),{' -b '},int2str(b(:)));
回答2:
A slightly simpler solution:
strcat(num2str([a(:) b(:)],'-a %d -b %d'), {})
来源:https://stackoverflow.com/questions/2366680/how-can-i-create-a-cell-of-strings-out-of-a-meshgrid-in-matlab