我有1x1000向量,由1和0组成。 我想在向量中找到四个连续的0并用0和1的组合替换它(例如,1101,1111,1010从1到15的二进制值的任意组合)但是我不应该替换或影响已经存在的1的在向量中。
答案 0 :(得分:2)
快速概念,滚动窗口查看每个4元素块并检查零数组。
%calling your vector "A" here
searchlen= 4 - 1; %remove 1 so when adding to index, takes correct # elements
zarray= zeros(1,searchlen+1);
for i=1:(length(A)-searchlen)
if(isequal(A(i:i+searchlen),zarray))
A(i:i+searchlen) = [1 0 0 1]; %replace with your code
end
end
答案 1 :(得分:2)
您可以使用STRFIND查找所有四个连续零的位置
%# binary row-vector
x = [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0];
%# starting locations of four-consecutive zeros
idx = strfind(x, [0 0 0 0]);
%# random binary numbers (rows) used to replace the consecutive zeros
n = dec2bin(randi([1 15],[numel(idx) 1]),4) - '0';
%# linear indices corresponding to the consecutive-zeros
idx = bsxfun(@plus, idx', (0:3));
%'# replace the 4-zeros
xx = x;
xx(idx(:)) = n(:);
结果:
>> x
x =
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
\_______1st_______/
>> xx
xx =
1 1 0 1 0 1 1 1 1 0 1 1 0 1 1
\_______1st_______/
>> n
n =
1 0 1 0 <-- 1st consecutive four-zeros replaced by this
1 1 1 0 <-- 2nd
1 0 1 1 etc...
请注意,如果初始向量x
包含长度超过4
的连续零,则strfind
将返回该较长序列中的多个位置。因此,根据您希望从较长的序列中选择4
(首次出现,最后出现等等),需要进一步处理。