Reputation: 3980
From the following example:
x = 1 + (10-1)*rand(1,100);
x(12:22) = 20 + (30-20)*rand(1,11);
x(70:94) = 20 + (30-20)*rand(1,25);
Here I am attempting a couple of things. Firstly I am trying to find the row number for the first value that is greater than 20 where the number of successive values >20 is more than 24. So in this example I would like to return the row number 70.
I can do this by:
y = x > 20;
k = [strfind([~y(1),y],[0 1]);strfind([y,~y(end)],[1 0])];
idx = k(1,diff(k) + 1 > 24);
However, I would also like to replace the first set of values (which did not include more than 24 successive values > 20) to nan. How can I achieve this?
Upvotes: 1
Views: 1758
Reputation: 32920
As for the first part of your question, here's a one-liner for finding all the indices of 25 or more successive occurrences of elements greater than 20:
idx = strfind((x(:)' > 20), ones(1, 25));
Use idx(1)
to obtain the first index, which is 70 in your example.
As for the second part of your question, here's a solution:
idx_start = strfind([0, x(:)'] > 20, [0 1]); %# Start indices
len = strfind([x(:)' > 20, 0], [1 0]) - idx_start + 1; %# Sequence lengths
first = find(len < 25, 1); %# First desired sequence
x(idx_start(first):idx_start(first) + len(first) - 1) = NaN;
Note that this replaces only the first successive occurences of x > 20, which are no more than 24.
Upvotes: 1
Reputation: 11168
You already have a fine solution for finding idx
, maybe find is better suited, I don't know:
y = x > 20;
kstart = find(diff([0 y])==1);
kend = find(diff([y 0])==-1);
klen = kend-kstart+1;
idx = kstart(find(klen>=24,1,'first')); %*
*yes, I know you can omit 'first'
, but it's there for clarity.
Anyway: to replace the first set of values (those who have index<idx
) use:
x(1:idx-1) = NaN;
Or if you meant to only replace all the numbers larger than 20 before idx
:
x(y(1:idx-1)) = NaN;
Upvotes: 3
Reputation: 4732
I'd like to the set of already good solutions.
You could use a convolution as well:
tmp = conv(x>20, ones(1,25));
inds = find(tmp==25)
first_indes = inds(1);
Upvotes: 1