What is the idomatic way to modify 2d matrices

Is there an idomatic way to fill in values in the 'var' variable below to match the values of the 'op' variable by avoiding loops to do so as much as possible?

fn test() {
    let mut var: Array2<f64> = Array2::zeros((2,6));
    let op: Array2<f64> = Array2::from_shape_vec((2,6), 
                                                  vec![2,7,5,2,7,5,2,7,5,
                                                       3,1,0,3,1,0,3,1,0]).unwrap();
}

Your question is not quite clear to me. Do you want to copy the data from op to var or do you want to do some sort of transformation? Do you want to start with the code in question and add something in the end that writes to var (reading from op) or is your goal to avoid the need to create op in the first place? Is the motivation for “avoiding loops” one that you want concise readable code, so just not write a loop yourself, or would there also be any issue with calling existing API that uses a loop internally?

i would like the "var" variable transformed (values assigned to index positions) so that it matches the values in the "op" variable. I'm looking for a function here equivalent to "repmat" in matlab to populate values in a 2d array

Seems like the .assign method might be what you’re looking for.

use ndarray::{Array2, array};

fn main() {
    let mut var: Array2<f64> = Array2::zeros((2, 6));
    let op: Array2<f64> = array![
        [2., 7., 5., 2., 7., 5.],
        [3., 1., 0., 3., 1., 0.],
    ];

    var.assign(&op);

    println!("var:\n{}", var);
}

(playground)

In case you want to start out with the smaller 2x3 array in op and repeat it twice, you could work with chunk-iterators and call assign in a simple for loop like

use ndarray::{Array2, array};

fn main() {
    let mut var: Array2<f64> = Array2::zeros((2, 6));
    let op: Array2<f64> = array![
        [2., 7., 5.],
        [3., 1., 0.],
    ];

    for mut chunk in var.exact_chunks_mut(op.dim()) {
        chunk.assign(&op);
    }

    println!("var:\n{}", var);
}

(playground)

2 Likes

No i meant more like using the repmat option to transform 'var' to 'op' such that

assert_eq!(var, op);

More variables can be used to transform 'var' to 'op' like the following

a = vec![2., 7., 5.];
b = vec![3., 1., 0.];

Edit: your 2nd solution was what i was looking for! thanks! :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.