Reputation: 6427
I would like to take an integer n
defining the number of bits in my communication code and a vector defining the alphabet I am assigning to bits 0:n-1
, and output a matrix/cell array containing the alphabetic notation for each state, i.e.:
function M = mycommarray(3,[-1,1])
produces
M = [{-1,-1,-1}, {-1,-1,1}...]
I tried doing this an easier way with dec2bin(0:7,3)
, but there doesn't seem to be a quick way to make the zeros into -1
s.
Is there anything close to prepackaged that does this? In this case I don't want anyone to make it for me (related to homework).
Upvotes: 3
Views: 489
Reputation: 6015
You can also do it like this:
M = 2 * (dec2bin(0:7, 3)=='1')-1;
That returns:
M =
-1 -1 -1
-1 -1 1
-1 1 -1
-1 1 1
1 -1 -1
1 -1 1
1 1 -1
1 1 1
However, it's slower. I get 0.0012s (dec2bin
) against 0.0002s (meshgrid
+bitget
) for 1024 values and 10 bits.
Upvotes: 1
Reputation: 32920
dec2bin
is actually not the best way to approach the problem, because its result is an array of strings (i.e a matrix of characters), where each digit is a character. If you want '-1'
to represent a logical "0", that would be two characters, and it introduces problems.
Consider an alternative method with bitget
. Making use of Shai's suggestion, do the following:
[bits, values] = meshgrid(1:3, 0:7);
M = 2 * bitget(values, bits) - 1;
The will produce what you want:
M =
-1 -1 -1
1 -1 -1
-1 1 -1
1 1 -1
-1 -1 1
1 -1 1
-1 1 1
1 1 1
Upvotes: 6
Reputation: 114786
To easily convert zeros to -1
(and leave the ones intact) you can simply do
minusOnes = 2 * zeroOnes - 1;
Upvotes: 1