简体   繁体   English

c ++相当于matlab max(find(array <x)和min(find(array> x)

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

what would be the c++ equivalent to this matlab code? 什么是这个matlab代码的c ++等价物? I started it off but i'm not sure what value B would be, i think A is correct. 我开始了,但我不确定B会是什么价值,我认为A是正确的。

MATLAB MATLAB

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

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

C++ attempt C ++尝试

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. 并在循环之前将B初始化为array.size

Essentially, you are finding the element with the lowest index in the array which is also larger than 1 - 1.0e-2 . 实质上,您发现数组中索引最低的元素也大于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. 类似的逻辑适用于第一部分,但您需要设置A = i+1而不是递增k因为无法保证数组已排序。

Basically the command A = max(find(array < 1.0e-2)); 基本上命令A = max(find(array < 1.0e-2)); Is looking for the largest index of the array that is greater than 1.02e-2. 正在寻找大于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. array < 1.0e-2)返回逻辑索引的向量。

find( ... ) converts the logical indices to numeric indices find( ... )将逻辑索引转换为数字索引

max(...) returns the largest value from the list of numeric indices. max(...)返回数字索引列表中的最大值。

A C++ equivalent would look something like: C ++等价物看起来像:

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: 要让B只是设置另一个循环:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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