Component-wise boolean operations and indexing with nalgebra

96 Views Asked by At

As an example for what I'm trying to replicate in Rust with nalgebra, consider the following Python code using NumPy:

import numpy as np

value = np.array([1.0, 2.0, 3.0])
error = np.array([0.01, 0.01, 0.01])

current_value = np.array([2.0, 3.0, 4.0])
current_error = np.array([0.1, 0.001, 0.001])
    
improved = current_error < error
value[improved] = current_value[improved]
error[improved] = current_error[improved]

print(error)
print(value)

Two vectors of errors are compared to each other. Then, for any components where the error decreased, the previous error and value is replaced with the current one. It is done by a component-wise boolean operation that produces the intermiediate vector improved, which can then be used to index the other vectors.

This kind of indexing doesn't seem to be possible with nalgebra, so I currently only have this basic loop solution:

use nalgebra::{dvector};

fn main() {
    let mut value = dvector![1.0, 2.0, 3.0];
    let mut error = dvector![0.01, 0.01, 0.01];

    let current_value = dvector![2.0, 3.0, 4.0];
    let current_error = dvector![0.1, 0.001, 0.001];
    
    for i in 0..error.len() {
        if current_error[i] < error[i] {
            value[i] = current_value[i];
            error[i] = current_error[i];
        }
    }

    println!("{}", error);
    println!("{}", value);
}

It works fine, but I wonder if there are there more elegant ways to achieve this? Any iterator/zip contraption I tried ended up way too complicated.

0

There are 0 best solutions below