如何在MATLAB中用其他数字替换矩阵的某些元素? [英] How can i replace some elements of a matrix by other numbers in MATLAB?
问题描述
我有一个由1000个二进制元素组成的矩阵,如Matlab中所示:
I have a matrix consists of 1000 binary elements like below in Matlab:
M = 11001100101100001011010001001100101000101110010110001100001010101100101110111001 ...
M = 11001100101100001011010001001100101000101110010110001100001010101100101110111001...
我如何分割每3个元素并用另一个元素替换它们.例如000 By 000000
,110 By 000001
,001 By 00001
,100 By 0001
,101 By 001
,010 By 01
,011 By 1
.
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))
推荐答案
M
此处是使用1000
二进制元素随机生成的:
M
here is randomly generated with 1000
binary elements:
rng(1);
M = randi([0 1], 1,1000);
fprintf('%d\n',M)
首先,我对M
进行零填充以达到3的长度倍数.其次,我将矩阵重新排列为每行3个元素的矩阵,并应用了Lookup_Out
.
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
这篇关于如何在MATLAB中用其他数字替换矩阵的某些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!