MATLAB Answers

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?

  0 Comments

Sign in to comment.

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.

  3 Comments

Deepak Gupta
Deepak Gupta on 23 Apr 2020
Use:
index = find(A>5)
to find indices where these values exist.
Reinder Dorman
Reinder Dorman on 24 Apr 2020
Ah yes, but there is a conditional beforehand, basically to check if more than 4 samples are bigger than X. I'll update the question.
I guess i've been working a bit too much on this thing that I've forgot that the basic premise of what i'm doing. But yeah, I forgot to mention this extra conditional that also in this piece of code.
Deepak Gupta
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.

Community Treasure Hunt

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

Start Hunting!

Translated by