Matlab对不同连续的同一数字赋值

比如一组数(1 1 0 2 2 0 0 0 2 1 2 2 2 2 1 1 1 2 2 2 0)
对2进行赋值
对于连续出现少于等于两个的2赋值为1
连续出现大于等于三个的2赋值为0
数组变成(1 1 0 1 1 0 0 0 1 1 0 0 0 0 1 1
1 0 0 0 0)
求赐教这个代码怎么写,谢谢🙏

详细的代码实现及解释如下,望采纳

% 定义数组
arr = [1 1 0 2 2 0 2 1 2 2 2 2 1 1 1 2 2 2 0];

% 对连续的数字进行赋值
count = 1;
for i = 2:length(arr)
    if arr(i) == arr(i-1)
        count = count + 1;
    else
        if arr(i-1) == 2
            if count <= 2
                arr(i-count:i-1) = 1;
            else
                arr(i-count:i-1) = 0;
            end
        end
        count = 1;
    end
end

% 对最后一段连续的数字进行赋值
if arr(end) == 2
    if count <= 2
        arr(end-count+1:end) = 1;
    else
        arr(end-count+1:end) = 0;
    end
end

% 输出结果
disp(arr);

代码中,我们使用了一个循环来遍历数组中的每个元素,并使用一个计数器来记录连续的数字数量。如果当前数字和上一个数字相同,那么计数器就加一;如果不同,就对上一段连续的数字进行赋值,并将计数器重置为 1。最后,还要注意最后一段连续的数字,因为最后一段数字在循环中不会被处理。

% Define the input array
arr = [1 1 0 2 2 0 2 1 2 2 2 2 1 1 1 2 2 2 0];

% Initialize a new array to store the result
result = arr;

% Set the threshold for the number of consecutive 2s
threshold = 2;

% Initialize a counter to keep track of the number of consecutive 2s
count = 0;

% Loop through the elements of the array
for i = 1:length(arr)
   % Check if the current element is a 2
   if arr(i) == 2
       % Increment the counter
       count = count + 1;
   else
       % If the current element is not a 2, reset the counter
       count = 0;
   end
   
   % Check if the number of consecutive 2s meets the threshold
   if count <= threshold
       % If it does, assign a value of 1 to the current element
       result(i) = 1;
   elseif count > threshold
       % If it does not, assign a value of 0 to the current element
       result(i) = 0;
   end
end

% Display the result
disp(result)
arr = [1 1 0 2 2 0 2 1 2 2 2 2 1 1 1 2 2 2 0];
cou = 1;
while cou<length(arr)
    if arr(cou)==2
        pos = 1;
        while arr(cou+pos)==2
            pos = pos +1;
        end
        if pos < 3
            arr(cou:cou+pos-1)=1;
        elseif pos > 2
            arr(cou:cou+pos-1)=0;
        end
        cou = cou + pos;
    else
        cou = cou + 1;
    end    
end
disp(arr);

给个python的
import itertools as it

l = [1, 1, 0, 2, 2, 0, 2, 1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 0]
res = it.groupby(l)

pos = 0
for i, v in res:
    lng = len(list(v))
    if i == 2 and lng < 3:
        l[pos:pos+lng] = [1] * lng
    elif i == 2 and lng > 2:
        l[pos:pos+lng] = [0] * lng
    pos += lng
print(l)

matlab 赋多个值,C和MATLAB中:同时对多个变量连续赋值
借鉴下
https://blog.csdn.net/weixin_31319027/article/details/116511635