Reputation: 91
I have a matrix consists of 1000 binary elements like below in Matlab:
M = 11001100101100001011010001001100101000101110010110001100001010101100101110111001...
How i can split every 3 elements and replace them By another elements. for example 000 By 000000
, 110 By 000001
, 001 By 00001
, 100 By 0001
, 101 By 001
, 010 By 01
, 011 By 1
.
I used this method but it doesn't work. What is wrong with it?
Lookup_In = [ 000 110 001 100 101 010 011 ] ;
Lookup_Out = {'000000','000001','00001','0001','101','01','1' } ;
StrOut = repmat({'Unknown'},size(M)) ;
[tf, idx] =ismember(M, Lookup_In) ;
StrOut(tf) = Lookup_Out(idx(tf))
Upvotes: 1
Views: 68
Reputation: 602
M
here is randomly generated with 1000
binary elements:
rng(1);
M = randi([0 1], 1,1000);
fprintf('%d\n',M)
First, I zeropadded M
to reach a length multiple of 3. Second, I reshaped the array in a matrix with 3 elements of each row and applied Lookup_Out
.
c = mod(numel(M),3);
M = [M,zeros(1,3-c)]; %zeropadding to multiple of 3
M = reshape(M,[3,numel(M)/3])';
Lookup_In = [ 000 110 001 100 101 010 011 ] ;
Lookup_Out = {'000000','000001','00001','0001','101','01','1' } ;
StrOut = repmat({''},[1,size(M,1)]);
for r=1:size(M,1)
StrOut{r} = Lookup_Out{str2double(sprintf('%d',M(r,:))) == Lookup_In};
end
Upvotes: 1