在Matlab中将数组映射到逻辑数组

时间:2017-04-19 11:27:51

标签: arrays matlab indexing

让我们说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的位置,数组索引为{ {1}}重置,因此它从头开始,也就是逻辑从0开始a从开头开始并继续为a array

2 个答案:

答案 0 :(得分:1)

您可以使用diff查找b更改的位置,然后使用arrayfuna生成索引:

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 :(得分:1)

您可以使用for循环并跟踪0数组的状态(1b):

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