gpt4 book ai didi

matlab - 根据序列大小替换重复值 - Matlab

转载 作者:行者123 更新时间:2023-12-05 05:41:57 28 4
gpt4 key购买 nike

我有一个由 1 和 0 组成的二维矩阵。

mat = [0 0 0 0 1 1 1 0 0
1 1 1 1 1 0 0 1 0
0 0 1 0 1 1 0 0 1];

我需要在每一行中找到所有连续重复的 1,并在序列大小小于 5(5 个连续的 ones)时用零替换所有 1:

mat = [0 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0];

我们非常欢迎任何关于如何解决这个问题的建议。

最佳答案

您可以使用 diff 找到 1 的运行的起点和终点,以及基于此的一些逻辑来将太短的运行归零。请参阅下面的代码和相关注释

% Input matrix of 0s and 1s
mat = [0 0 0 0 1 1 1 0 0
1 1 1 1 1 0 0 1 0
0 0 1 0 1 1 0 0 1];
% Minimum run length of 1s to keep
N = 5;

% Get the start and end points of the runs of 1. Add in values from the
% original matrix to ensure that start and end points are always paired
d = [mat(:,1),diff(mat,1,2),-mat(:,end)];
% Find those start and end points. Use the transpose during the find to
% flip rows/cols and search row-wise relative to input matrix.
[cs,r] = find(d.'>0.5); % Start points
[ce,~] = find(d.'<-0.5); % End points
c = [cs, ce]; % Column number array for start/end
idx = diff(c,1,2) < N; % From column number, check run length vs N

% Loop over the runs which didn't satisfy the threshold and zero them
for ii = find(idx.')
mat(r(ii),c(ii,1):c(ii,2)-1) = 0;
end

如果您想放弃易读性,可以根据完全相同的逻辑将其压缩为速度稍快、密度更高的版本:

[c,r] = find([mat(:,1),diff(mat,1,2),-mat(:,end)].'); % find run start/end points
for ii = 1:2:numel(c) % Loop over runs
if c(ii+1)-c(ii) < N % Check if run exceeds threshold length
mat(r(ii),c(ii):c(ii+1)-1) = 0; % Zero the run if not
end
end

关于matlab - 根据序列大小替换重复值 - Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72172964/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com