2017-04-20 78 views
1

讓我們假設一個數組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。在Matlab中使用邏輯陣列映射陣列

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] 

回答

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)