How can I use equality in xt::filter?

Viewed 61

the following code,

#include <iostream>

#include "xtensor/xadapt.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xindex_view.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xmasked_view.hpp"
#include "xtensor/xview.hpp"

using namespace std;

int main() {
    xt::xarray<float> a = {{1, 2, 3}, {4, 2, 6}, {9, 0, 2}};
    cout << a << endl;
    xt::filter(a, a == 2) = 10;
    cout << a << endl;
}

Fails to compile with the following: error: no match for ‘operator==’ (operand types are ‘xt::xarray<float>’ ... and ‘int’)

However, other comparison operators work as expected (>,<,>=,<=). I'm not sure if operator== was intentionally not implemented, but until it is (if it ever is), is there a work around, and what is it?

2 Answers

You can use xt::equal(a, b) instead of a == b. I.e.

xt::filter(a, xt::equal(a, 2)) = 10;

does what you want.

xtensor provides logical operators like && and ||. Combining these with the allowed comparisons results in the same output as expected by '==' or '!='.

specifically a >= 2 && a <= 2 <=> a == 2 and a > 2 || a < 2 <=> a != 2

so my final program is

#include <iostream>

#include "xtensor/xadapt.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xindex_view.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xmasked_view.hpp"
#include "xtensor/xview.hpp"

using namespace std;

int main() {
    xt::xarray<float> a = {{1, 2, 3}, {4, 2, 6}, {9, 0, 2}};
    cout << a << endl;
    xt::filter(a, a >= 2 && a <= 2) = 10;
    cout << a << endl;
}

and it's output is

{{ 1.,  2.,  3.},
 { 4.,  2.,  6.},
 { 9.,  0.,  2.}}
{{  1.,  10.,   3.},
 {  4.,  10.,   6.},
 {  9.,   0.,  10.}}
Related