在Matlab中使用逻辑数组映射数组

时间:2017-04-20 07:50:54

标签: arrays matlab indexing mapping

让我们说一个数组a=[1,2,3,4,5,6,7,8]和一个逻辑数组b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1],如何得到[1,1,1,1,2,3,2,1,1,1,2,3,4,5,6,7,8,8,8],其中有一个数组a继续相反的方向,其中在零处左移,对于零,它从索引值的相反索引方向继续。它保留为1。

array         a=[1,2,3,4,5,6,7,8]
logical array b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1]
how to  get     [1,1,1,1,2,3,2,1,1,1,2,3,4,5,6,7,8,8,8]

1 个答案:

答案 0 :(得分:3)

我不知道它是否是最优雅的方式,但它确实有效:

a = [1,2,3,4,5,6,7,8];
len = length(a);
b = [1,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1];
% find when b changes from 0 to 1
bb = [0 diff(b)];
c = b; c(c == 0) = -1;
c(bb == 1) = 0;
% cumsum finds initial indexes
d = cumsum(c);
% truncate indexes if exceeds array
while 1
    ix = find(d < 1 | d > len,1,'first');
    if isempty(ix)
        break;
    end
    if d(ix) < 1
        d(ix:end) = d(ix:end) + 1;
    else
        d(ix:end) = d(ix:end) - 1;
    end
end
res = a(d)