1

I have a function that manipulates a Vector<float> resulting a new Vector<float> with different length, an example would be appending a number in front of the vector

let addElementInfront (x:Vector<float>) =
    x.ToArray() 
    |> Array.append [|x.[0]|]
    |> vector

Now I want to apply this to all the rows of a (2x2) matrix and I would expect a (2x3) matrix, I tried to use the Matrix.mapRows of MathNet.Numerics.LinearAlgebra but it gives me error that the size needs to be the same.

Just wonder if MathNet has any other function to map rows that results a different size matrix.

Thanks.

Jose Vu
  • 621
  • 5
  • 13

1 Answers1

3

It seems you are trying to duplicate the first column of the matrix. For example:

1.0; 2.0         1.0; 1.0; 2.0
3.0; 4.0 becomes 3.0; 3.0; 4.0

If this is true, then the code could be:

let m = matrix [ [ 1.0; 2.0 ]
                 [ 3.0; 4.0 ] ]
m
|> Matrix.prependCol (m.Column 0)

UPDATE

Because the assumption above is not true.

So you can get the seq of the matrix rows, then transform it as usual with Seq.map, and finally make the result matrix:

let transform f m =
    m
    |> Matrix.toRowSeq
    |> Seq.map f
    |> matrix

// or even shorter in F# idiomatic style:
let transform f =
    Matrix.toRowSeq >> Seq.map f >> matrix

// test

let addElementInFront (x : Vector<float>) =
    x.ToArray()
    |> Array.append [| x.[0] |]
    |> vector

matrix [ [ 1.0; 2.0 ]
         [ 3.0; 4.0 ] ]
|> transform addElementInFront
Nghia Bui
  • 3,694
  • 14
  • 21
  • 1
    hi Nghia, thanks for your comment. The case I laid out is just an example that the function will transform the size of the vector, it needs not to be the exact. My question was to find the mapRows function that map this function ```Vector->Vector``` to ```Matrix->Matrix``` where the result matrix has different size than the original. – Jose Vu Nov 14 '18 at 09:10
  • wow it works like a charm, i didn't know the toRowsSeq, also didn't know seq.map can apply on vector. Thanks bro, I marked your comment as the answer – Jose Vu Nov 14 '18 at 23:50