1

I want to place the binary equivalent number for each element side - by side i.e, the final matrix Concatenated_A would be of size m by nbits*n where [m,n] = size(A);

A = [5, 5,  4,  10, 4;
    10, 10, 10, 10, 5;

    ];

I did an attempt but the result is wrong. I need help in correctly implementing the concatenation. Thank you

[m,n] = size(A);
numbits = 4;
for m = 1:M

Abin = dec2bin(A(m,:),numbits);
for j = 1:size(Abin,1)
Concatenated_A(m,:) = Abin(j,:);
end

end

For first row in A(1,:) = 5, 5, 4, 10, 4 ; its decimal conversion of each element would give a matrix as below.

0   1   0   1
0   1   0   1
0   1   0   0
1   0   1   0
0   1   0   0

Then, how can I do something like this :

Concatenated_A(1,:) = [0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 0 1 0 0]

The above operation is repeated for every row in A.

1 Answer 1

1

You can transpose the result of dec2bin so that the binary representation goes down the columns and then reshape this into the desired shape so that each row is on it's own row. After reshaping, we take the transpose again so that the rows go across the rows again. Also we need to be sure to transpose A before we start so that we encode along the rows.

out = reshape(dec2bin(A.', numbits).', [], size(A, 1)).'
%   01010101010010100100
%   10101010101010100101

Or if you want a logical matrix instead you can compare your character array to the character '1'

out = reshape(dec2bin(A.', numbits).', [], size(A, 1)).' == '1'
%   0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 0 1 0 0
%   1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1
Sign up to request clarification or add additional context in comments.

1 Comment

@SrishtiM Oops! I'd missed a transpose! Fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.