 # Calculating roots, companion matrix

#1

Hello,

I don’t know if it’s the best idea (I’m not well versed in linear algebra and scientific computing), but I’m thinking of using nalgebra to compute roots, in a similar way to Numpy

I’m wondering what the best way is to construct the companion matrix https://en.m.wikipedia.org/wiki/Companion_matrix

I see that there’s ways to create a diagonal matrix, but the companion matrix needs it to be offset. I guess I can manually do the offset and use something like `from_vec`, but wanted to check if there was an easier way.

Thanks!

#2

Hi!

I see that there’s ways to create a diagonal matrix, but the companion matrix needs it to be offset. I guess I can manually do the offset and use something like `from_vec` , but wanted to check if there was an easier way.

If I understand correctly, what you want is to able to create a matrix with its first lower subdiagonal (instead of the diagonal itself) set to 1? If so, then there is no dedicated function for doing this but there are several possible approaches:

1. Using the `::from_fn` constructor:
``````DMatrix::from_fn(num_rows, num_cols, |i, j| if i == j + 1 { 1.0 } else { 0.0 })
``````
1. Or using a loop to set the components you need:
``````let mut mat = DMatrix::zeros(num_rows, num_cols);
for i in 1..num_rows {
mat[(i, i - 1)] = 1.0;
}
``````
1 Like