MATLAB Answers

How to concatenate an array of numbers without for loop

8 views (last 30 days)
JFz
JFz on 22 Mar 2018
Commented: JFz on 22 Mar 2018
Hi, I have an array of integer numbers A = [1, 2, 3]. I would like to concatenate the numbers for use in SQL statement like '(1, 2, 3)'. How to do that without a for loop? Thanks.

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 22 Mar 2018
>> A = [1,2,3];
>> str = sprintf(', %d',A);
>> str = sprintf('(%s)',str(3:end))
str = (1, 2, 3)

  0 Comments

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 22 Mar 2018
A = [1 2 3];
sprintf('(%s)', strjoin(compose('%d', A), ', '))

  3 Comments

JFz
JFz on 22 Mar 2018
Thanks. Got an error Undefined function or variable 'compose'.
Guillaume
Guillaume on 22 Mar 2018
compose was introduced in version R2016b. (You should say in your question if you're several versions behind).
In earlier versions, you can replace compose by the undocumented sprintfc:
sprintf('(%s)', strjoin(sprintfc('%d', A), ', '));
Or use Stephen's method of using sprintf then removing the initial ', '.

Sign in to comment.

Sign in to answer this question.

Products