MATLAB Answers

concatenate all value in a matrix into one number

2 views (last 30 days)
Terek Li
Terek Li on 17 Oct 2016
Commented: Guillaume on 17 Oct 2016
if I have a matrix [1 2 3 4], is there a quick and easy way to obtain 1234 ?

  0 Comments

Sign in to comment.

Accepted Answer

Thorsten
Thorsten on 17 Oct 2016
This works even if the numbers are not single digits, i.e., in in {1,2,...,9}
v = [10 20 4];
num = sscanf(sprintf('%d', v), '%f')

  1 Comment

Guillaume
Guillaume on 17 Oct 2016
Indeed, however if they are single digits (as I assumed), conversion to string and back to number is going to be several order of magnitude slower than simple mathematical manipulation.
Not that it matters for such trivial code.

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 17 Oct 2016
v = [1 2 3 4];
assert(all(v >= 0 & v < 10 & mod(v, 1) == 0), 'elements of v are not single digits');
sum(10.^(numel(v)-1:-1:0) .* v)

  0 Comments

Sign in to comment.

Tags


Translated by