根据特定值左右选择矩阵中的n个元素

时间:2014-05-26 09:57:47

标签: arrays matlab matrix

我有一个逻辑矩阵A,我想选择给定固定距离的每个1s值左边的所有元素。让我们说我的距离是4,我想(例如)用固定值(说2)替换A中每个1左边的所有4个单元格。

A= [0 0 0 0 0 1 0
   0 1 0 0 0 0 0
   0 0 0 0 0 0 0
   0 0 0 0 1 0 1]

B= [0 2 2 2 2 1 0
   2 1 0 0 0 0 0
   0 0 0 0 0 0 0
   2 2 2 2 2 2 1]

在B中是我想要的,考虑到也是过度的(B中的最后一行),以及在我的1左边只有1个值而不是4作为固定搜索距离(第二行)的情况。

4 个答案:

答案 0 :(得分:8)

这个可爱的单行怎么样?

n = 3;
const = 5;
A = [0 0 0 0 0 1 0;
     0 1 0 0 0 0 0;
     0 0 0 0 0 0 0;
     0 0 0 0 1 0 1]

A(bsxfun(@ne,fliplr(filter(ones(1,1+n),1,fliplr(A),[],2)),A)) = const

结果:

A =

     0     0     5     5     5     1     0
     5     1     0     0     0     0     0
     0     0     0     0     0     0     0
     0     5     5     5     5     5     1

这里有一些解释:

Am = fliplr(A);                      %// mirrored input required
Bm = filter(ones(1,1+n),1,Am,[],2);  %// moving average filter for 2nd dimension
B = fliplr(Bm);                      %// back mirrored
mask = bsxfun(@ne,B,A)               %// mask for constants
A(mask) = const

答案 1 :(得分:3)

以下是您可以提出的简单解决方案:

w=4;                            % Window size
v=2;                            % Desired value

B = A;
for r=1:size(A,1)               % Go over all rows
  for c=2:size(A,2)             % Go over all columns
    if A(r,c)==1                % If we encounter a 1
       B(r,max(1,c-w):c-1)=v;   % Set the four spots before this point to your value (if possible)
    end
  end
end

答案 2 :(得分:2)

d = 4; %// distance
v = 2; %// value

A = fliplr(A).'; %'// flip matrix, and transpose to work along rows.
ind = logical( cumsum(A) ...
    - [ zeros(size(A,1)-d+2,size(A,2)); cumsum(A(1:end-d-1,:)) ] - A );
A(ind) = v;
A = fliplr(A.');

结果:

A =
     0     2     2     2     2     1     0
     2     1     0     0     0     0     0
     0     0     0     0     0     0     0
     2     2     2     2     2     2     1

答案 3 :(得分:2)

方法#1 使用图像处理工具箱提供的 imdilate 一行 -

A(imdilate(A,[ones(1,4) zeros(1,4+1)])==1)=2

<强>解释

步骤1:创建一个与imdilate一起使用的形态结构元素 -

morph_strel = [ones(1,4) zeros(1,4+1)]

这基本上代表一个窗口向左延伸n个位置,右边有1个n位,包括带零的原点。

第2步:使用imdilate修改A,以便我们在{{1}左侧的所有四个位置1 1A -

imdilate_result = imdilate(A,morph_strel)

步骤3:1的每个A选择所有四个索引并将其设置为2 -

A(imdilate_result==1)=2

因此,可以将此方法的一般形式写为 -

A(imdilate(A,[ones(1,window_length) zeros(1,window_length+1)])==1)=new_value

对于给定数据,window_length4new_value2


方法#2 使用 bsxfun -

%// Paramters
window_length = 4;
new_value = 2;

B = A' %//'
[r,c] = find(B)
extents = bsxfun(@plus,r,-window_length:-1)
valid_ind1 = extents>0
jump_factor = (c-1)*size(B,1)
extents_valid = extents.*valid_ind1
B(nonzeros(bsxfun(@plus,extents_valid,jump_factor).*valid_ind1))=new_value
B = B' %// B is the desired output
相关问题