Filter löschen
Filter löschen

concatenate all value in a matrix into one number

1 Ansicht (letzte 30 Tage)
Terek Li
Terek Li am 17 Okt. 2016
Kommentiert: Guillaume am 17 Okt. 2016
if I have a matrix [1 2 3 4], is there a quick and easy way to obtain 1234 ?

Akzeptierte Antwort

Thorsten
Thorsten am 17 Okt. 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 Kommentar
Guillaume
Guillaume am 17 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 17 Okt. 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)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by