1

Consider the following vectors:

>> signals

signals =

 1
 1
 1
 1
 0
 0
 0
 0
 1
 1
 1
 1
 0
 0
 0
 0

>>exits

exits =

 2
10

What I need to do is set the 1s to 0s in the signal matrix from each value in exits until the value in signals changes. For example, where exits=2, I would set the 1s to 0s in the signal vector at indicies 2, 3, and 4.

What I have done so far is to identify where the values change in the signal vector so that I can identify the start and stop index. For example:

>> find(diff(signals)~=0)

ans =

 4
 8
12

By doing this, I know I have to set the 1s to 0s from exits=2 to signals=4 and exits=10 to signals=12. I am stuck however in figuring out how to do this with no loops.

I realize this may be a bit vague, so here is a simpler example:

>> signals

signals =

 1
 1
 1
 1
 1
 0
 0
 0
 1
 1
 1

>> exit

exit =

 3

>> rst=exit:find(diff(signals)~=0)

rst =

 3     4     5

signals =

 1
 1
 0
 0
 0
 0
 0
 0
 1
 1
 1

I am basically trying to generalize this simple example to cases where there are multiple exit values and multiple different sequences of signals.

4

1 回答 1

2

循环肯定会是更简单、更易读的解决方案。没有循环的方法是重建signals-array,保持开始并丢弃冗余exits

signals = [
 1
 1
 1
 1
 1
 0
 0
 0
 1
 1
 1];

exit = 3;

startEnd = diff([0;signals]);

%# add the new exit
startEnd(exit) = -1;

%# remove redundant "exits"

startEndIdx = find(startEnd);

deltaEvent = diff([0;startEnd(startEndIdx)]);

deltaIsZero = deltaEvent == 0; %# these are the bad exits

startEnd(startEndIdx(deltaIsZero)) = 0;

%# now we can reconstruct the signals vector
signals = cumsum(startEnd)

signals =

     1
     1
     0
     0
     0
     0
     0
     0
     1
     1
     1
于 2012-09-23T12:49:10.197 回答