How to change the 7th least significant of a binary code?

I had created a cell array of size <1x368cell>.
Each element of an array contains a binary code such as '11100101'.
I want to change the 7th bit of this code with an external value.
How could I do it?
Please help me.

 Accepted Answer

Hi Himanshu Nailwal
binary codes can be represented with characters (translating numeric values with dec2bin) or also with logical values.
We can put logical values in cell fields in many different ways.
Since you haven not supplied the variable, let me start with
A={mod(dec2bin(randi([64 900],10,1)),2)}
A =
[10x10 double]
this could have been built in other ways. Now despite the Workspace Value reads 1x1 cell
A{1}
=
0 1 0 0 0 1 1 0 0 1
1 0 1 1 0 1 1 1 0 1
0 1 1 0 1 0 1 0 0 1
1 1 0 0 1 1 1 0 1 0
0 0 1 1 0 1 1 0 0 0
0 1 0 0 0 1 1 1 0 0
0 0 1 0 1 1 1 0 0 1
0 0 1 0 1 1 0 0 0 1
1 1 0 0 0 1 0 1 1 1
1 0 0 0 1 0 0 1 0 1
each code of yours is stored separately, not in char type, but logical bits.
To read one binary code
A{1}(1,:)
=
0 1 0 0 0 1 1 0 0 1
to read 4 least significant bits
A{1}(1,[end-3:end])
=
1 0 0 1
to read a single bit, the first bit of the first code
A{1}(1,1)
=
0
or the 8th bit of the 4th code
A{1}(4,8)
=
0
so, to access a particular bit across all codes,
A{1}([1:end],4)
=
0
1
0
0
1
0
0
0
0
0
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
appreciating time and attention
John BG

More Answers (2)

T = cell2mat(YourCell(:));
T(:,7) = new values
NewCell = reshape( mat2cell(T, ones(1, size(T,1)), size(T,2)), 1, []);

2 Comments

T = cell2mat(YourCell(:));
T(:,7) = 1
NewCell = reshape( mat2cell(T, ones(1, size(T,1)), size(T,2)), 1, []);
This gives an error and the output is as '1110011'.
How to correct it? Please help.
"new values" needs to be '1' not 1. You are not using numeric values for your representation: you are using the characters '0' and '1'

Sign in to comment.

There are many ways:
for idx = 1:numel(yourcellarray)
yourcellarray{idx}(7) = '1';
end
cellarrayaschar = char(yourcellarray);
cellarrayaschar(:, 7) = '1';
yourcellarray = cellstr(cellarrayaschar);
yourcellarray = cellfun(@(b) [b(1), '1', b(3:end)], yourcellarray, 'UniformOutput', false);
and more...

Categories

Asked:

on 11 Feb 2017

Answered:

on 12 Feb 2017

Community Treasure Hunt

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

Start Hunting!