user1855165
user1855165

Reputation: 289

How can I combine numbers in a row into a single number

A = [7,2,3,4,4]

I want to combine them to:

B = 72344

I am new to matlab. Is there any build in function that can do that? Thanks in advance.

Upvotes: 3

Views: 1096

Answers (4)

chappjc
chappjc

Reputation: 30579

You can apply num2str and strrep as follows:

>> A = [7,2,3,4,4];
>> B = str2num(strrep(num2str(A(:)'),' ',''))
B =
    72344

Note that A(:)' is used to ensure a row vector. However, webpat's answer is more concise since you can leave off the ' and strrep is not required. Also, the mathematical solution by damienfrancois seem more elegant than using strings.

Upvotes: 1

damienfrancois
damienfrancois

Reputation: 59120

Here is a solution

>> A = [7,2,3,4,4];
>> B=A*(10.^(length(A)-1:-1:0))'
B =  72344

Note @BenVoigt's comment:

>> A = [7,2,3,4,4;2,3,4,5,3]
A =

   7   2   3   4   4
   2   3   4   5   3

>> B=A*(10.^(length(A)-1:-1:0))'
B =

   72344
   23453

Upvotes: 4

webpat
webpat

Reputation: 1949

    zz = str2num(num2str(A(:))')

zz =

       72344

is straightforward

Upvotes: 2

s.bandara
s.bandara

Reputation: 5664

You could also simply add '0' as a shift into the range of numeric characters: A+'0'. Then, B = str2double(char(A+'0')).

Upvotes: 1

Related Questions