找到分组在数组中的特定零 - matlab

时间:2015-02-22 19:18:46

标签: arrays matlab matrix indexing zero

我有一个像这样的数组

a=[0 0 0 1 1 1 1 0 0];

并希望社区能够找到一种优雅的方式来查找第一组中0的最后一次出现以及最后一组零中第一次出现0。请注意,两组零之间总是存在一些。答案应该是这样的

b=[0 0 1 0 0 0 0 1 0];

4 个答案:

答案 0 :(得分:3)

基于 strfind 的方法可以很好地与数字数组一起找到像这样的模式,看起来非常适合解决它。这是实施 -

%// Find indices where we have matches of [0 1] and [1 0] corresponding to
%// the two cases as listed in the question
case1_idx = strfind(a,[0 1])
case2_idx = strfind(a,[1 0])

%// Initialize output array; set those required positions in it as ones
b = zeros(size(a))
b([case1_idx(1) case2_idx(end)+1]) = 1

示例运行 -

a =
     0     0     0     1     1     1     1     0     0
b =
     0     0     1     0     0     0     0     1     0

答案 1 :(得分:2)

这个描述性解决方案如何:

afterA = [a(2:end),nan]
beforeA = [nan,a(1:end-1)]

b = (a==0 & afterA==1) | (a==0 & beforeA==1)

答案 2 :(得分:2)

d = diff(a)
res = zeros(size(a))
res(find(d==1)) = 1
res(find(d==-1)+1) = 1

或(假设a始终以0开头和结尾),您甚至不需要搜索整个数组

res = zeros(size(a))
res(find(a, 1, 'first')-1) = 1
res(find(a, 1, 'last')+1) = 1

答案 3 :(得分:1)

卷积:

b = zeros(size(a)); %// initiallize
x = conv(2*a-1,[1 -1],'same'); %// convolution
b(find(x==2)) = 1; %// last zero in a run
b(find(x==-2)+1) = 1; %// first zero in a run

或者您可以使用diff而不是conv使用相同的方法:

b = zeros(size(a)); %// initiallize
c = diff(a); %// compute differences
b(find(c==1)) = 1; %// last zero in a run
b(find(c==-1)+1) = 1; %// first zero in a run