MATLAB Answers

Change the binary number of a specific group of matrix elements by switching from zero to one and vice versa

23 views (last 30 days)
erfan nori
erfan nori on 14 Jan 2021
Commented: erfan nori on 15 Jan 2021
Hi
Please help me how to make a 5x5 matrix whose members are all binary numbers,
For example, select the matrix even elements and then if the binary number is 1111000, convert it to 00001111, in other words, convert one to zero and convert zero to one.
r = 4×4
11001100 11011100 10000010 10010110
10100000 11011000 11010100 10011100
11011001 11001101 10001001 11001011
10001001 11111101 10011100 11111001
convert to
r = 4×4
11001100 00100011 10000010 01101001
10100000 00100111 11010100 01100011
11011001 00110010 10001001 00110100
10001001 00000010 10011100 00000110

  6 Comments

Show 3 older comments
erfan nori
erfan nori on 14 Jan 2021
In fact, it is the same number as 5, but I want each integer to be a binary number with 8 bits, so I have displayed it as 00000101.
Image Analyst
Image Analyst on 14 Jan 2021
So, for example you did this:
>> r = uint8(randi(255, 4, 4))
r =
4×4 uint8 matrix
12 81 98 125
25 243 196 114
210 9 203 165
178 112 48 181
The values of r are 8 bits if you use dec2bin() to convert them to binary character arrays.
Can you please save your r in a .mat file
save('answers.mat', 'r');
and attach it with the paper clip icon?
James Tursa
James Tursa on 15 Jan 2021
It sounds as though you have some data that you would like converted, and you have come up with a scheme for converting it but need help with one part of that scheme. Instead of this approach, why don't you tell us what the original data is (size and class), and what you want for a result. Dealing with these intermediate strings you may have created might not be the best overall approach.

Sign in to comment.

Accepted Answer

Mohammad Sami
Mohammad Sami on 15 Jan 2021
Edited: Mohammad Sami on 15 Jan 2021
If your data is int / uint, you can use the function bitcmp to get the bitwise complement.
a = uint8(1);
b = bitcmp(a);
dec2bin(a,8)
dec2bin(b,8)

  2 Comments

Walter Roberson
Walter Roberson on 15 Jan 2021
bitcmp is a good idea.
If you happen to need to do the negation for some bits but not others, then you can use exclusive or against a pattern that has 1 in the places to flip. You can also always write bitcmp in terms of bitxor, but bitcmp is theoretically faster if you are doing all the bits.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!