Convert float64 array to float32 array - arrays

I have an array of float64 and want to convert each value to float32.
I've tried:
# What I have
features64 [120]float64
# What I've tried
features32 = [120]float32(features64)
But that gives the compile error:
cannot convert features (type [120]float64) to type [120]float32

For example,
package main
func main() {
var features64 [120]float64
var features32 [len(features64)]float32
for i, f64 := range features64 {
features32[i] = float32(f64)
}
}

You can't convert one slice/array type to another. You'll need to create a new array and iterate over the original converting each element:
for i,f := range features64 {
features32[i] = float32(f)
}

Simply
var arr1 [120]float64
var arr2 [120]float32
for i, v := range arr1 {
arr2[i] = float32(v)
}

Related

Convert [MLMultiArray] to Float?

I have an MLMultiArray which is a result of an ML Model.
I need to convert it to Float so that I can further store it in Realm.
Below is an example of one of the MLMultiArray. The result from the ML Model contains 120 of the same vectors so its an array of MLMultiArrays i.e Array of Float32 1 x 128 matrices.
Float32 1 x 128 matrix
[4.476562,1.179688,0.07141113,6.976562,-0.2858887,-7.378906,0.6445312,3.695312,1.399414,2.486328,-3.988281,-0.2636719,1.000977,-4.480469,-7.832031,1.59082,0.8515625,-1.296875,-1.435547,7.839844,5.851562,0.3701172,-2.492188,7.273438,2.404297,-3.3125,-5.699219,-0.6816406,0.2807617,-3.882812,-3.982422,5.339844,4.125,-3.871094,0.6225586,1.712891,-10.02344,0.7119141,4.472656,3.566406,-0.559082,-1.049805,-4.679688,10.07812,-1.459961,4.707031,-6.078125,1.675781,-0.6259766,2.519531,3.472656,-3.400391,-6.714844,-4.933594,-1.733398,1.095703,-6.15625,9.234375,3.693359,-9.492188,0.8637695,0.8203125,-2.814453,-4.4375,-1.092773,3.332031,0.1623535,3.583984,-11.25781,-0.9941406,-0.3491211,1.464844,-1.579102,4.558594,2.703125,4.601562,5.914062,-2.402344,-5.46875,-0.355957,11.39062,2.070312,-7.289062,-0.4470215,-0.1595459,9.148438,1.833008,-2.097656,-3.9375,6.699219,-4.347656,-6.835938,-1.179688,3.910156,-13.07812,-1.947266,-0.9238281,-0.949707,-4.398438,2.363281,4.421875,4.632812,2.607422,8.773438,0.9106445,9.21875,-14.0625,-1.301758,-4.875,0.6054688,6.496094,-2.021484,3.898438,-4.644531,0.9853516,7.253906,3.066406,-1.051758,-8.09375,-6.527344,3.890625,5.175781,0.3701172,-0.5683594,-1.341797,0.1497803,4.074219,0.5932617]
Is there any way I can convert an array of MLMultiArray to Float32?
Any help would be appreciated <3
You can first convert the MLMultiArray to an UnsafeBufferPointer and then to a regular Array.
import CoreML
var a: [Float] = [ 1, 2, 3 ]
var m = try! MLMultiArray(a)
if let b = try? UnsafeBufferPointer<Float>(m) {
let c = Array(b)
print(c)
}
This is old question but this can help someone:
To convert from an MLMultiArray To An Array of primitive, You can use this function you will need just to change the output type
func convertToArray(from mlMultiArray: MLMultiArray) -> [Double] {
// Init our output array
var array: [Double] = []
// Get length
let length = mlMultiArray.count
// Set content of multi array to our out put array
for i in 0...length - 1 {
array.append(Double(truncating: mlMultiArray[[0,NSNumber(value: i)]]))
}
return array
}
To convert from an Array to MLMultiArray Use this, you may need to change the shape accordingly
func convertToMLMultiArray(from array: [Double]) -> MLMultiArray {
let length = NSNumber(value: array.count)
// Define shape of array
guard let mlMultiArray = try? MLMultiArray(shape:[1, length], dataType:MLMultiArrayDataType.double) else {
fatalError("Unexpected runtime error. MLMultiArray")
}
// Insert elements
for (index, element) in array.enumerated() {
mlMultiArray[index] = NSNumber(floatLiteral: element)
}
return mlMultiArray
}
I'm using this way, and subscript to access the element and it works fine for me.
const float *array = (float*)matrix.dataPointer

Golang convert interface{} to array of N size

I have an array of T wrapped in an interface. I know the size of the array beforehand. How do I write a generic function that gets back an array (or a slice) for any array length? E.g. for size 3 I want something like
var values interface{} = [3]byte{1, 2, 3}
var size = 3 // I know the size
var _ = values.([size]byte) // wrong, array bound must be a const expression
I can't really do a type switch because [1]byte is a different type from [2]byte etc so I'd have to explicitly enumerate all possible sizes.
Reflect is your friend here:
package main
import (
"fmt"
"reflect"
)
func main() {
var in interface{} = [3]byte{1, 2, 3} // an element from your []interface{}
var size = 3 // you got this
out := make([]byte, size) // slice output
for i := 0; i < size; i++ {
idxval := reflect.ValueOf(in).Index(i) // magic here
uidxval := uint8(idxval.Uint()) // you may mess around with the types here
out[i] = uidxval // and dump in output
}
fmt.Printf("%v\n", out)
}
Slices are the better choice output here, since you indicate that you have an undefined length.
What Magic here does is indexing the value of your input interface through reflect. This is not quick, but it does the trick.

N-Dimensional array swift

Is there any way to have an n dimensional array in swift? I would like to be able to make a function that creates an array with n dimensions but I cannot figure out how.
Basically something like this:
func ndarray <T> (dimensions: Int...) -> [[T]] { // What do I tell it I return?
var out
for d in dimensions {
out = Array<T>(repeating: out, count: d)
}
return out
}
The above code does not work for obvios reasons but, I think it points out the main problems I am having:
How do I define a return type
How do I actually create the array
Once created how do I traverse and populate the array
Here is the implementation of an N-Dimensional Array. It uses a normal array internally for storage and converts the multi-dimensional indices into a single index for the internal array.
struct NDimArray<T> {
let dimensions: [Int]
var data: [T]
init(dimensions: Int..., initialValue: T) {
self.dimensions = dimensions
data = Array(repeating: initialValue, count: dimensions.reduce(1, *))
}
init(dimensions: Int..., initUsing initializer: () -> T) {
self.dimensions = dimensions
data = (0 ..< dimensions.reduce(1, *)).map { _ in initializer() }
}
// Compute index into data from indices
private func computeIndex(_ indices: [Int]) -> Int {
guard indices.count == dimensions.count else { fatalError("Wrong number of indices: got \(indices.count), expected \(dimensions.count)") }
zip(dimensions, indices).forEach { dim, idx in
guard (0 ..< dim) ~= idx else { fatalError("Index out of range") }
}
var idx = indices
var dims = dimensions
var product = 1
var total = idx.removeLast()
while !idx.isEmpty {
product *= dims.removeLast()
total += (idx.removeLast() * product)
}
return total
}
subscript(_ indices: Int...) -> T {
get {
return data[computeIndex(indices)]
}
set {
data[computeIndex(indices)] = newValue
}
}
}
Example:
// Create a 3 x 4 x 5 array of String with initial value ""
var arr = NDimArray<String>(dimensions: 3, 4, 5, initialValue: "")
for x in 0 ..< 3 {
for y in 0 ..< 4 {
for z in 0 ..< 5 {
// Encode indices in the string
arr[x, y, z] = "(\(x),\(y),\(z))"
}
}
}
// Show internal storage of data
print(arr.data)
["(0,0,0)", "(0,0,1)", "(0,0,2)", "(0,0,3)", "(0,0,4)", "(0,1,0)", "(0,1,1)", "(0,1,2)", "(0,1,3)", "(0,1,4)", "(0,2,0)", "(0,2,1)", "(0,2,2)", "(0,2,3)", "(0,2,4)", "(0,3,0)", "(0,3,1)", "(0,3,2)", "(0,3,3)", "(0,3,4)", "(1,0,0)", "(1,0,1)", "(1,0,2)", "(1,0,3)", "(1,0,4)", "(1,1,0)", "(1,1,1)", "(1,1,2)", "(1,1,3)", "(1,1,4)", "(1,2,0)", "(1,2,1)", "(1,2,2)", "(1,2,3)", "(1,2,4)", "(1,3,0)", "(1,3,1)", "(1,3,2)", "(1,3,3)", "(1,3,4)", "(2,0,0)", "(2,0,1)", "(2,0,2)", "(2,0,3)", "(2,0,4)", "(2,1,0)", "(2,1,1)", "(2,1,2)", "(2,1,3)", "(2,1,4)", "(2,2,0)", "(2,2,1)", "(2,2,2)", "(2,2,3)", "(2,2,4)", "(2,3,0)", "(2,3,1)", "(2,3,2)", "(2,3,3)", "(2,3,4)"]
print(arr[2, 2, 2]) // "(2,2,2)"
print(arr[3, 0, 0]) // Fatal error: Index out of range
print(arr[0, 4, 0]) // Fatal error: Index out of range
print(arr[2]) // Fatal error: Wrong number of indices: got 1, expected 3
Initializing an Array with a Reference Type
As #DuncanC noted in the comments, you have to be careful when initializing an array with a value which is a reference type, because the array will be filled with references to the object and modifying the object at any index will modify all of them.
To solve this, I added a second initializer:
init(dimensions: Int..., initUsing initializer: () -> T)
which takes a closure () -> T which can be used to create a new object for each element of the array.
For example:
class Person {
var name = ""
}
// Pass a closure which creates a `Person` instance to fill the array
// with 25 person objects
let arr = NDimArray(dimensions: 5, 5, initUsing: { Person() })
arr[3, 3].name = "Fred"
arr[2, 2].name = "Wilma"
print(arr[3, 3].name, arr[2, 2].name)
Fred Wilma
Nope, it's not possible. Array dimensions is something that needs to be determined at compile time, while the argument you want to pass to the initializer will not be known until runtime. If you really want to achieve something like this, then you'll need to move the array indexing from compile time to runtime, e.g. by accessing the array via an array of indexes. Still you don't have compile validation, since the array length can at runtime to not match the dimensions of the array.
This problem is similar to the one that attempts to convert a tuple to an array.

go 1d array combine 2d array with append

I have two one dimensional array and I want to combine the two single arrays into one multi dimensional array with append.
How would this be done for the fastest in go?
val time []int64
val value []float64
val 2darray [][]int64, float64
Would append be the best way to do this in go?
Here's an example of how it can be done:
package main
import (
"fmt"
)
type TimeAndValue struct {
time int64
value float64
}
func main() {
times := []int64{0, 1, 2, 3, 4}
values := []float64{1.23, 2.34, 3.45, 4.56, 5.67}
timesAndValues := zip(times, values)
fmt.Println(timesAndValues)
}
func zip(ts []int64, vs []float64) []TimeAndValue {
if len(ts) != len(vs) {
panic("not same length")
}
var res []TimeAndValue
for i, t := range ts {
res = append(res, TimeAndValue{time: t, value: vs[i]})
}
return res
}
https://play.golang.org/p/1OWJ1HG1XL

Go: range and len of multidimensional array?

Is it possible to use range and len on a multidimensional array?
Either with var a [3]int8 or
package main
func main () {
var a [3][5]int8
for h := range a {
println(h)
}
println(len(a))
}
Both produce
0
1
2
3
?
Thanks to dystroy's answer, here's an example of writing and reading a 3-dimensional array i was able to adapt (posting here because I had much trouble finding any examples of this, so maybe this will help someone else):
package main
func main() {
var a [3][5][7]uint8
//write values to array
for x, b := range a {
for y, c := range b {
for z, _ := range c {
a[x][y][z] = uint8(x*100+y*10+z)
}
}
}
//read values from array
for _, h := range a {
for _, i := range h {
for _, j := range i {
print(j, "\t")
}
println()
}
println()
}
}
In Go as in most languages, what you call a multidimensional array is an array of arrays. The len operator only gives you the length of the "external" array.
Maybe the var declaration could be clearer for you if you see it as
var a [3]([5]int8)
which also compiles. It's an array of size 3 whose elements are arrays of size 5 of int8.
package main
import "fmt"
func main() {
var a [3][5]int8
for _, h := range a {
fmt.Println(len(h)) // each one prints 5
}
fmt.Println(len(a)) // prints 3, the length of the external array
}
outputs
5
5
5
3
To loop safely through the whole matrix, you can do this :
for _, h := range a {
for _, cell := range h {
fmt.Print(cell, " ")
}
fmt.Println()
}
If you need to change the content, you may do
for i, cell := range h { // i is the index, cell the value
h[i] = 2 * cell
}
The solution with range is already provided so i'll talk about how to use length (len) to go through a multi-dimesional array in golang.
So if u have an array arr[][] :
[1,2,3]
[4,5,6]
Now the len(arr) will output = 2.
while len(arr[1]) will output = 3.
Sample code is provided here : https://play.golang.org/p/XerzPhkQrhU
No, the first one produces 0,1,2 ( index of in the range )
http://play.golang.org/p/0KrzTRWzKO
And the second one produces 3 ( the length of the array ).
http://play.golang.org/p/0esKFqQZL0
In both cases you're using the outermost array.

Resources