如何在MATLAB中用其他数字替换矩阵的某些元素?

时间:2017-11-11 07:02:14

标签: matlab matrix replace binary

我有一个由Matlab中的1000个二进制元素组成的矩阵:

  

M =   11001100101100001011010001001100101000101110010110001 10000101010110010111 0111001 ...

我如何分割每3个元素并用另一个元素替换它们。例如000 By 000000110 By 000001001 By 00001100 By 0001101 By 001010 By 01011 By 1

我使用了这种方法,但它不起作用。这有什么问题?

  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))

1 个答案:

答案 0 :(得分:1)

M此处随机生成1000二进制元素:

rng(1);
M = randi([0 1], 1,1000);
fprintf('%d\n',M)

首先,我使用M来达到3的长度倍数。其次,我将数组重新整形为矩阵,每行包含3个元素并应用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