简体   繁体   中英

How to use index in MATLAB to find function constraints

I want to return the indices of elements which satisfy some conditions and the condition that their index should be between some constants A and B . There is a naive form of implementing this with:

inds=find(conditions)
real_inds=find(A<=inds<=B)

but it is inefficient and actually I want to limit my search to elements with index between those constants, not all elements.

how about restricting yourself to the range A , B ?
Suppose you have my_vector and you wish to find the elements larger than 0.3 and smaller than 0.5 (the " conditions "). Limiting yourself to the range A , B is simply:

masked_ind = find(my_vector(A:B) > 0.3 & my_vector(A:B) < 0.5);
real_ids = masked_ind + A - 1; %// correct the offset induced by `A`.

By applying the conditions on my_vector(A:B) you actually don't care how big is my_vector and you are only processing elements in the range A:B .


BTW, have you considered using logical indexing , as suggested by Andras Deak , instead of using find and the actual linear indices?

%// create a mask to keep indices from A to B only
real_inds_logical = false(size(your_vector));
real_inds_logical(A:B) = (my_vector(A:B)>0.3 & my_vector(A:B)<0.5);

You can do something like this:

Suppose that you have vector x , conditions: x == 7 or ( x > 3 and x < 5) and you want the search between A and B.

Now define vector g as an auxiliar vector of indices:

g = 1:length(x);

And then get your indices like this:

indices = g( (g >= A) & (g <= B) & (conditions) );

That in this case is translated to:

indices = g( (g >= A) & (g <= B) & (x == 7 | (x > 3 & x < 5)) );

This will return the elements of g that satisfice the conditions between the extern parenthesis.


An example code :

Initial values:

x = [0.0975  0.2785  0.5469  0.9575  0.9649  0.1576  0.9706  0.9572  0.4854  0.8003];
A = 4;
B = 9;

Conditions: x >= 0.1 and x <= 0.7

Code:

g = 1:length(x);
indices = g((g >= A) & (g <= B) & (x <= 0.7) & (x >= 0.1));

Result:

indices =

 6     9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM