2017-04-19 63 views
2

比方說一個array a=[1,3,8,10,11,15,24]logical array b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1],如何讓[1,1,3,1,3,8,1,3,8,1,2,3,8,10],看到邏輯b變爲1 a重置數組索引所以它從一開始就開始,也同樣在那裏邏輯就變得開始從0開始a array並繼續作爲1,3,8,10..etc.映射一個數組邏輯陣列中的Matlab的

回答

1

可以使用diff以找到b變化,然後用arrayfun生成索引a

a=[1,3,8,10,11,15,24]; 
b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1]; 
idxs = find(diff(b) ~= 0) + 1; % where b changes 
startidxs = [1 idxs]; 
endidxs = [idxs - 1,length(b)]; 
% indexes for a 
ia = cell2mat(arrayfun(@(x,y) 1:(y-x+1),startidxs,endidxs,'UniformOutput',0)); 
res = a(ia); 
1

可以使用一個for循環和跟蹤b陣列的狀態(01):

a = [1,3,8,10,11,15,24]; 
b = [1,0,0,1,1,1,0,0,0,1,1,1,1,1]; 

final = [] 
index = 0; 
state = b(1); 
for i = 1:numel(b) 
    if b(i) ~= state 
     state = b(i); 
     index = 1; 
    else 
     index = index+1; 
    end 
     final = [final, a(index) ]; 
end