Combining two number to one number
Afficher commentaires plus anciens
Dear Matlab users
Im facing the problem of combining two seperate numbers into one number. Let's say i have the number 1 and 2 and want to combine them in that order, resulting in 12. Another example could be 4 and 6, yielding 46, or 3, 6 and 7 yielding 367.. Is there any smart or simple way of doing this?
Thanks in advance, Poul
Réponse acceptée
Plus de réponses (2)
Image Analyst
le 28 Déc 2014
Use sprintf():
a = 1;
b = 2;
c = 3;
str = sprintf('%d%d%d', a, b, c) % If you want a string.
doubleStr = str2double(str) % If you want a double.
1 commentaire
Stephen23
le 10 Jan 2019
Simpler and more versatile to just have one '%d' specifier:
str = sprintf('%d', a, b, c)
Poul Reitzel
le 29 Nov 2011
2 votes
6 commentaires
Andrei Bobrov
le 29 Nov 2011
b = [3 6 7]
out = b*10.^(numel(b)-1:-1:0).'
Marc Gebhardt
le 10 Jan 2019
Thats bad. It only works for one-digit numbers obviously.
A C
le 16 Mai 2019
How does this work?
out = [30 60 70].^[2; 1; 0]
[ 900 3600 4900
30 60 70
1 1 1 ]
Image Analyst
le 17 Mai 2019
Not sure what exactly you mean by "how", but the first column is
30^2 = 900
30^1 = 30
30^0 = 1
The second column is
60^2 = 3600
60^1 = 60
60^0 = 1
The third column is
70^2 = 4900
70^1 = 70
70^0 = 1
Or maybe one can just say the "how" is done by normal element-by-element operations that you should be well familiar with in MATLAB (as opposed to matrix operations which do not use the dot before the operater).
A C
le 19 Mai 2019
hello, Image Analyst
I was talking about this code. It returns 367
b = [3 6 7]
out = b*10.^(numel(b)-1:-1:0)'
I thought this would look like this
out = [30 60 70].^[2; 1; 0]
but it returns a matrix.
Why are the two codes different. How does the first code return a single number?
Image Analyst
le 19 Mai 2019
Well, it would be good if you had given that equation for "out" in your first post so we'd have known about it.
It's because the first vector is a row vector and the second is a column vector (because of the '). And you're using a recent version of MATLAB that does automatic expansion. Look up expansion here or in MATLAB to see what that means.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!