Hi,
I have a 1 x N double array and I would like to merge it to become a 1 x 1 array.
E.g.
K = [0,1,1,1];
I want K to become K = [0111];
How do I do it?
Hi,
I have a 1 x N double array and I would like to merge it to become a 1 x 1 array.
E.g.
K = [0,1,1,1];
I want K to become K = [0111];
How do I do it?
Here's a cute way of doing it in one line:
>> K = [1 2 3 4];
>> K*10.^(length(K)-1:-1:0)'
ans =
1234
EDIT: new, super short way now.
From your example I'm guessing you just want to concatenate the elements of a vector (seeing that k=[0111]
actually stores the number 111
). Therefore if you want to keep them as they are, we use a string instead:
>> K = [0,1,1,1];
>> str = sprintf('%d', K)
str =
0111
>> whos str
Name Size Bytes Class Attributes
str 1x4 8 char
Since you are merging an array of zeroes and ones into a single value, you're going to have trouble representing it properly as a double value. This is because any leading zeroes on the left hand side of the number won't be displayed when it's a double. However, you can represent the string of zeroes and ones as a character array. A neat little trick for doing this is as follows:
>> K = [0,1,1,1];
>> char(K+'0')
ans =
0111
When you add a vector of doubles (K
) and a scalar string ('0'
), the string gets converted to it's ASCII/Unicode value (48
in this case). K+'0'
becomes the vector [48 49 49 49]
, and the CHAR function changes these values to their equivalent ASCII/Unicode characters, creating a character array.