Scala sum of the arrays contained in an array - arrays

I have defined a function that receives an array of arrays. I want to get the sum of all arrays. My question is how to make that sum.
def suma[T](args: WrappedArray[T]*)(implicit n: Numeric[T]) = {
args.transpose.map(_.sum)
}
def sum[T](arr: WrappedArray[WrappedArray[T]])(implicit n: Numeric[T]) = {
val result = suma( ______ )
}
I thought I use the defined "sum" , but not how to pass the contents of the container array. Like there is a much simpler way to do this. Any ideas?

To get "sum of all arrays" you want .flatten, not .transpose.
args.flatten.sum should do it.
Or are you asking how to call a function with vargargs? For that, you need a splat operator:
val result = suma(arr:_*)

Related

What is the fastest way of converting a numpy array to a ctype array?

Here is a snippet of code I have to convert a numpy array to c_float ctype array so I can pass it to some functions in C language:
arr = my_numpy_array
arr = arr/255.
arr = arr.flatten()
new_arr = (c_float*len(arr))()
new_arr[:] = arr
but since the last line is actually a for loop and we all know how notorious python is when it comes to for loops for a medium size image array it takes about 0.2 seconds!! so this one line is right now the bottle neck of my whole pipeline. I want to know if there is any faster way of doing it.
Update
Please note "to pass to a function in C" in the question. To be more specific I want to put a numpy array in IMAGE data structure and pass it to rgbgr_image function. You can find both here
The OP's answer makes 4 copies of the my_numpu_array, at least 3 of which should be unnecessary. Here's a version that avoids them:
# random array for demonstration
my_numpy_array = np.random.randint(0, 255, (10, 10))
# copy my_numpy_array to a float32 array
arr = my_numpy_array.astype(np.float32)
# divide in place
arr /= 255
# reshape should return a view, not a copy, unlike flatten
ctypes_arr = np.ctypeslib.as_ctypes(arr.reshape(-1))
In some circumstances, reshape will return a copy, but since arr is guaranteed to own it's own data, it should return a view here.
So I managed to do it in this weird way using numpy:
arr = my_numpu_array
arr = arr/255.
arr = arr.flatten()
arr_float32 = np.copy(arr).astype(np.float32)
new_arr = np.ctypeslib.as_ctypes(arr_float32)
In my case it works 10 times faster.
[Edit]: I don't know why it doesn't work without np.copy or with reshape(-1). So it would be awesome if anyone can explain.

Populating Array in Swift 4 with for-loop without using the index

I need to populate an Array (already declared and initialized) using a for loop in order to create a determinate amount of items.
I ended up with the following code:
func createValues() -> Array<Int> {
let usableRange:Range = 6..<11;
var arrayOfValues: Array<Int>=[]; //Array declared and initialized
for i in 0..<10 {
arrayOfValues.append(random(usableRange));
print(arrayOfValues[i]);
}
return arrayOfValues;
}
this code does what I expect it to do just fine. However, as soon as I comment out the line
print(arrayOfValues[i]);
Xcode throws the following warning:
Immutable value 'i' was never used; consider replacing with '_' or
removing it
If I accept the suggestion the code works, but not as fine as it did before.
I'm just transitioning from Obj-C to Swift and I don't really know what the proper way to do this should be. Any help would be appreciated. Thanks in advance.
P.S. I'm aware that I don't need semicolons anymore, but old habits die hard, I guess...
Since you don't use i, you can just write
for _ in 0 ..< 10
The _ means "yes, there is a value, but I don't care about it", here and in many other situations.
If you want just a good alternative for your code, I'm offering you this:
var i: Int = 0
while i < 10 {
arrayOfValues.append(random(usableRange))
i += 1
}
If the goal is to generate an array of random numbers in your given range, I would suggest you simply generate it directly. There is no need for the for loop.
let usableRange = UInt32(6)..<UInt32(11)
let arr = (0..<10).map { _ in Int(
arc4random_uniform(usableRange.upperBound - usableRange.lowerBound)
+ usableRange.lowerBound
)}
Array has a designated initalizer, which initalizes an array with a given size and a repeated value:
let values = Array(repeating: "VALUE", count: 5)
print(fiveZs)
// Prints "["VALUE", "VALUE", "VALUE", "VALUE", "VALUE"]"
Source: Apple Documentation

generalizing scalar inputs to array inputs for user-defined fucntions

The round function can take a scalar and operate on it. However it can also take an array and operate on it in expected manner.
>> round(2.3)
ans =
2
>> round([2.3,3.4])
ans =
2 3
I similarly have a function and want it to work in the ""expected"" manner for array inputs. It works well for scalar inputs. I could run a for loop and evaluate my function on each element of the array but what other smarter ways do i have available?
For further concreteness, i have:
function [a,b]=func(c,d,e,f)
And i have d,e,f but i want to evaluate the function to several values of c:-
g=[];
for i=1:10
[a,b]=func(c(i),d,e,f);
g=[g;[a,b]];
end
I am not fully sure how to apply arrayfun though i believe it is what i should use.
What you are looking for is the arrayfun function.
Here is the documentation: http://www.mathworks.com/help/matlab/ref/arrayfun.html
Say, I have this function:
function res = myTest(a,b)
size(a) % for checking that we work on each element
res = a+1;
res = res +b;
I have a matrix A
A = magic(3);
I want to apply myTest with a equal to each element in A
A1 = arrayfun(#(x) myTest(x,2),A)
(x is replaced by the elements of the array declared after the comma)

can the keyword "foreach" get the array parameter?

I am a beginner of the scala. many concepts aren't clear for me.
I want to ask that if the foreach can get (or control) the array parameter ?
for example:
val array = Array.ofDim[Double](2,6)
I can use for to control the array's parameter, like
for( i <- 0 until 2){
for(j <- 0 until 6){
......... }}
I can use i,j control and get the parameter. Is "foreach" can do that??
(I know foreach can do things without the parameter, but I just want to ask if it can get
the array parameter?)
thank you :)
I'm not exactly sure what you're asking. If you're asking how to loop over the full array item-by-item, then you can do that without nesting for comprehensions. This will print the contents of your 2D array:
for (row <- array; col <- row) println(col)
If you're asking how to loop over all the indices of the array (I think maybe that's what you mean when you say parameter), then you can use the indices property:
for (i <- array.indices; j <- array(i).indices) println(array(i)(j))
If you're just trying to do indexOf across a 2D array, you can probably just reuse the solution for indexOf for 2D Vector in Scala. This is how I'd adapt it to your code:
val array = Array.tabulate(2,6)(_*6+_)
val searchValue = 8
val indices: Option[(Int, Int)] =
(for {
i <- array.indices
j <- array(i).indices
if (array(i)(j) == searchValue)
} yield (i, j)).headOption
If none of the values match, you'll get indices = None. In this case there is a match, so you get indices = Some((1,2)), because 8 is at array(1)(2).
(Note: Unlike indexOf, using a for comprehension does not short-circuit as soon as it finds the solution. If you make the index ranges lazy by calling .iterator, .view or .toStream then you'll get the expected short-circuiting behavior.)
U can use the function [ indexOf(elem: T): Int ] that will return the position
Scala Array

Why Array's :+ does not work inside for comprehension?

val tagsArray = tags.split(",")
var trimmedTagsArray: Array[String] = Array()
for(tag <- tagsArray) {
trimmedTagsArray :+ tag.trim
}
trimmedTagsArray is empty afterwards, even though tagsArray contains elements, and even if I omit the trim call.
What am I missing here?
You need to understand the :+ operator. Rather than modifying the existing trimmedTagsArray variable, the :+ is actually returning a new array with the result of the expression "tag.trim" appended to the end. Since you neither yield this result back, or assign it anywhere, this value is discarded.
I believe what you are actually looking for is to replace the line in your for comprehension with the following.
trimmedTagArray = trimmedTagArray :+ tag.trim
While this will accomplish what you want, however, it is not the best solution by far. Instead, try the following...
val trimmedTagsArray = for(tag <- tagsArray) yield {
tag.trim
}
The above will create a val (preferred in Scala over var) that has the desired values while avoiding mutable state.
It works. Just that for(...) {} returns Unit. You want :
for(tag <- tagsArray) yield {
trimmedTagsArray :+ tag.trim
}

Resources