Indexing between values of a 2D vector?

2 views (last 30 days)
Reinder Dorman
Reinder Dorman on 23 Apr 2020
Edited: Deepak Gupta on 24 Apr 2020
say I have vector A, and I have some parts of this vector that I've identified to be true in a certain condition. For example, Lets say I want to find parts of the vector A that are bigger than 5, and I want it to be at least 4 consequetive samples after each other to be above 5. In the below example, let's say that i've found this between index 20 and 30, and 60 and 70. So lets say
A = rand(1,100) % just a random signal
crossThreshold = A > 5;
conditionArray = find(diff(crossThreshold));
% and lets say for some random signal there happens to be 2 patches above 5, from 20 to 30, so
conditionArray = [20 30; 60 70];
If I want to have the values in A corresponding with these parts, I'd generally say Id use the colon operator, like
A([20:30, 60:70])
Is there a nifty way to do this directly from the arrayy conditionArray? Intuitively I'd look for something like
A([conditionArray(:,1) : conditionArray(:,,,2)])
But this only give me the indices for the elements in the first row of conditionArray (in this case it gives 20:30)
I guess you could loop this, but I keep thinking there is a clever way to do this. Anyone have an idea?

Answers (1)

Deepak Gupta
Deepak Gupta on 23 Apr 2020
Edited: Deepak Gupta on 23 Apr 2020
Hi Reinder,
Yes, you can directly use conditions as index.
A = 100*rand(1,100);
X = A(A>5);
Here, X will contain all the values which satisfy the condition.
Deepak Gupta
Deepak Gupta on 24 Apr 2020
Edited: Deepak Gupta on 24 Apr 2020
I am not sure if there is a direct function to do it but i wrote a piece of code to do this. Code is self explanatory. Assuming A is your array. finalIndex gives the start Index and end Index .
B = A>5;
temp = diff([0 B 0]);
start_idx = find(temp == 1);
end_idx = find(temp == -1);
count = end_idx - start_idx;
end_idx = end_idx -1;
finalIndex = [start_idx(count>3)' end_idx(count>3)'];

Sign in to comment.


Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by