I am trying to display some value of n consecutive numbers of a vector (in this example, vector x).
x = [1
1
1
1
1
1
0
0
0
0
1
1
0
0
0
0
0
0
1
0
1
0
1
0
1
0
1
1
0
0
1
1
1
1
1
1
0
0
1
1
1
1
0
0
1
1
1
1
1
1
0
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
1
0
1
0
0
0
1
0
0
0
0
1
0
1
0
0
1
0
0
0
0
1
1
0
0
0
1
0
0
0
0
0
0
1
0
1
0
0
0
0
1
0
1
0
0
0
1
0
0
0
0
0
0
1
0
0
0
1
0
0
1
1
1
1
1
1
0
0
1
1
0
0
1
0
1
0
0
0
0
0
0
1
0
1
0
0];
For example, I may want the first 3 values of 4 consecutive numbers which would be (3 values of 4 bits each):
1111
1100
0011
I may want the first 4 values of 2 consecutive numbers which would be (4 values of 2 bits each):
11
11
11
00
x
is a double array. What would be an easy way to achieve this?
CodePudding user response:
The simplest way is to reshape x
to a matrix with your desired number of bits per value as the number of rows (MATLAB is column-major). For example, to get 4-digit values:
t = reshape(x,4,[]);
This will only work if the length of x
evenly divides into 4. You could first crop x
to the right number of elements to avoid errors where the length is not evenly divisible:
t = reshape(x(1:4*3),4,[]);
Now the transposed matrix t
, converted to a string, looks like your desired output:
c = char(t.' '0');
The output is a 3x4 char array:
'1111'
'1100'
'0011'
You can convert these binary representations back to numbers with bin2dec
:
b = bin2dec(c);
The output is a 3-element double vector:
15
12
3