echorand
echorand

Reputation: 47

Mapping Array With Logical Array In Matlab

Let's say an array a=[1,2,3,4,5,6,7,8], and a 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], where there is ones the array a continues in opposite direction where its was left at zeros, and for zeros it continues in opposite index direction from the index value it was left at ones.

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]

Upvotes: 1

Views: 61

Answers (1)

user2999345
user2999345

Reputation: 4195

i don't know if it's the most elegant way, but it works:

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)

Upvotes: 3

Related Questions