Jack Geraghty
Jack Geraghty

Reputation: 23

Rust ndarray: iterate over array in column order

I have a 2D array with shape (2, N), from the ndarray crate, of i16 audio samples (a stereo (2-channel) audio clip). The standard way that these values are written to a file is in column-major order, so every even entry belongs to channel 1 / row 0 and the odd elements correspond to channel 2 / row 2.

I'm sure there's a way of doing this without using column-major ordering, but it seems like this shouldn't be the case/necessary and that there is likely an idiomatic way to do this using the in-built crate functionality.

The crate documentation explicitly states that iter and iter_mut use row-major ordering, without the option of changing it.

Is there a way to achieve this in the ndarray crate, or do I need to do my own column order iteration?

Upvotes: 0

Views: 833

Answers (1)

frankenapps
frankenapps

Reputation: 8261

I am not sure I completly understood what you are trying to do, but I think you want either this

for row in data.columns() {
    for val in row.iter() {
        println!("{}", val);
    }
}

or that which is the other way round:

for column in data.rows() {
    for val in column.iter() {
        println!("{}", val);
    }
}

where data is your array.

Here is a link to rustexplorer.

P.S.: I think it would have benefited the question if you had provided example code and the expected output.

Upvotes: 0

Related Questions