简体   繁体   中英

c++ equivalent to matlab max(find(array < x) and min(find(array > x)

what would be the c++ equivalent to this matlab code? I started it off but i'm not sure what value B would be, i think A is correct.

MATLAB

array = (-1:.001:1)';

    A = max(find(array < 1.0e-2));
    B = min(find(array > 1 - 1.0e-2));

C++ attempt

for(i = 0; i < array.size; i++){
    if(array[i] < 1.0e-2){ 
    k++
    A = k;
   }
    if(array[i] > (1- 1.0e-2)){
    //not sure what to do here
    B = ?;
   }
}
for(i = 0; i < array.size; i++){  // Would be faster if you reversed loop direction
    if(array[i] < 1.0e-2)
        A = i;
}

for(i = 0; i < array.size; i++) {
    if(array[i] > 1-1.0e-2) {
        B = i;
        break;
    }
}

For the second bit, I would do this instead inside the same loop:

if(array[array.size-i-1] > (1 - 1.0e-2)) B = array.size - i;

and initialize B to array.size before the loop.

Essentially, you are finding the element with the lowest index in the array which is also larger than 1 - 1.0e-2 . If you start at the element with the highest index and then traverse the entire array and update each time you satisfy the criteria, you will end up with what you need. A similar logic applies for the first part, but you will need to set A = i+1 instead of incrementing k because there is no guarantee the array is sorted.

Basically the command A = max(find(array < 1.0e-2)); Is looking for the largest index of the array that is greater than 1.02e-2.

To see how this happens just break down the statement into parts:

array < 1.0e-2) returns a vector of logical indices.

find( ... ) converts the logical indices to numeric indices

max(...) returns the largest value from the list of numeric indices.

A C++ equivalent would look something like:

int A = -1;
int maxVal = 1.0e-2;
for (int i = array.length-1; i>=0; i--)
   if (array[i] < maxVal){
      A = i;
      break;
   }

To get B just setup another loop:

int B = -1;
int minVal = 1 - 1.0e-2;

for (int i=0; i<array.length; i++)
    if (array[i] > minVal){
        B = i;
        break;
     }

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