MATLAB Answers

How can I merge vector elements into a single number of type double?

2 ビュー (過去 30 日間)
Lazaros Ioakeimidis
Lazaros Ioakeimidis 2019 年 2 月 4 日
コメント済み: Guillaume 2019 年 2 月 5 日
Hello,
How can I transform this vector:
v=[1 2 3]
into this scalar of type double?:
k=123
Thank you,
Lazaros.

  0 件のコメント

Sign in to comment.

採用された回答

Guillaume
Guillaume 2019 年 2 月 4 日
編集済み: Guillaume 2019 年 2 月 4 日
k = polyval(v, 10)
is probably the easiest.
This assume of course that each element of v is an integer in the range [0-9].

  0 件のコメント

Sign in to comment.

その他の回答 (2 件)

Jan
Jan 2019 年 2 月 4 日
編集済み: Jan 2019 年 2 月 4 日
x = [1,2,3];
d = x * 10 .^ (numel(x)-1:-1:0).' % dot product

  0 件のコメント

Sign in to comment.


YT
YT 2019 年 2 月 4 日
編集済み: YT 2019 年 2 月 4 日
Something like this?
A = [1 2 3];
joined = str2num(strjoin(num2cell(num2str(A(:))),''));
%>> joined = 123 (type double)
There are probably some more elegant solutions, but this is what I came up with for now.

  3 件のコメント

Guillaume
Guillaume 2019 年 2 月 4 日
If you were going to go through strings and back, this would be simpler and faster:
str2num(char(A + '0'))
However, conversion of numbers to/from strings are slow (compared to just doing maths)
YT
YT 2019 年 2 月 4 日
Looks much better. Thanks, learned something new today. The only downside to this is that, like you stated in your polyval solution, that this also only works correctly for positive integers.
Guillaume
Guillaume 2019 年 2 月 5 日
Indeed but that is most likely the case I assume.
A simpler, yet more generic solution, using number->string->number conversion:
str2num(strjoin(compose('%d', A), ''))

Sign in to comment.

タグ


Translated by