I am trying to implement a function mapping shown in attached image but not working, pls correct me

1 view (last 30 days)
%{
my code not working ,pls correct me
question:
for i=0:1:15 output(A)
'0000' 00
'0001' 01
'0010' 10
'0011' 11
'0100' 11
'0101' 10
'0110' 01
'0111' 00
'1000' 00
'1001' 01
'1010' 10
'1011' 11
'1100' 11
'1101' 10
'1110' 01
'1111' 00
if msb-1==0; output=i(msb-2:end);
else msb-1==1; output=~i(msb-2:end); i.e., ones comp of i(msb-2:end)
%}
N=16;
m= 2^(log2(N)-2); % m=4
A=zeros(1,m);
j=zeros(1,m);
k=zeros(1,m);
for i=0:1:N-1
msb1= bitget(i,log2(N)-1); %msb1=msb-1
if(msb1==0)
j(i+1)=string(dec2bin(i)).extractAfter(1);
A(i+1)=bin2dec(j);
else
j(i+1)=string(dec2bin(i)).extractAfter(1);
k(i+1)=not(j-'0');
A(i+1)=bin2dec(k);
end
end
  3 Comments
VARDIREDDY
VARDIREDDY on 9 Sep 2022
sir ,
msb means 1st position from left .
msb-1 means 2nd position from left .
msb-2 means 3rd position from left .
let i=0:1:15
if msb-1 == 0 , output = 0,1,2,3
if msb-1 == 1 , output = 3,2,1,0
for i=0:1:15
msb-1==0 happens 2 times and
msb-1==1 happens 2 times
therefore
expected output= 0,1,2,3,3,2,1,0,0,1,2,3,3,2,1,0
i am getting following errors:
Error using bin2dec
Input argument must be a character vector, string, or cell array of character vectors.
Error in untitled7 (line 13)
A(i+1)=bin2dec(j);
pls suggest corrections in code

Sign in to comment.

Answers (1)

ag
ag on 10 Nov 2023
Edited: ag on 10 Nov 2023
Hi VARDIREDDY,
I understand that you need to implement the following logic:
if the 2nd MSB is 0, output= 3rd MSB to end, else output = One’s complement of 3rd MSB to end.
I’ve made a few changes to your code, as shown below:
N=16;
m= 2^(log2(N)-2); %m = 4
A = ['']; %empty character array for result
for i = 0:N-1
binStr = dec2bin(i, m); % Convert number to binary string
remStr = extractAfter(binStr, 2); %extract the 3rd MSB to end string
if(binStr(2)=='0') % check if the 2nd MSB is 0
A = [A; remStr]; % append the result to answer array
else
A = [A; char(not(remStr-'0') + '0')]; %append the one’s complement of the result to the answer array
end
end
A
A = 16×2 char array
'00' '01' '10' '11' '11' '10' '01' '00' '00' '01' '10' '11' '11' '10' '01' '00'
For more details, please refer to the following documentations:
Hope this helps!
Best Regards,
Aryan Gupta

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!