Slicing in 2D array in F # but similar to Matlab?
I was wondering if there is a way to use a list or int array as an index to slice into an array to get an additional array in f #.
I know you can do the following
Arr2d.[*,1] or Arr2d.[1..5,1..2] etc...
But I was looking for something like Matlab where you can write:
Arr2d([1;6;10],1) or Arr2d(1:10,[1;6;10])
Can I do slicing like in F #?
Thank!
Here is my test solution: (maybe not optimal, but works)
let sampleMatrix = Array2D.init 10 5 (fun x y -> y)
val sampleMatrix : int [,] = [[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]
[0; 1; 2; 3; 4]]
let idxlist = [1;3;4]
let array2dColumnSlice (idxlist:list<int>) (data:'T[,]) =
let tmp = [|for i in idxlist -> data.[*,i]|]
Array2D.init tmp.[0].Length tmp.Length (fun x y -> tmp.[y].[x] )
let slice = array2dColumnSlice idxlist sampleMatrix
val slice : int [,] = [[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]
[1; 3; 4]]
source to share
For ranges only, you can wrap Array2D with a cut type or use the old PowerPack type .
See the docs here: http://msdn.microsoft.com/en-us/library/dd233214.aspx#sectionToggle6
This slice syntax can be used for types that implement member accessor operators and overloaded GetSlice methods. For example, the following code creates a matrix type that wraps an F # 2D array, implements the Item property to support array indexing, and implements three versions of GetSlice. If you can use this code as a template for your matrix types, you can use all the slicing operations described in this section.
source to share