Is it possible to get non-contiguous slices from an ndarray? - matrix

Is it possible to index columns in a Rust ndarray matrix using a Vec rather than a Slice object? The only documentation I can find pertains to slicing using contiguous columns
Specifically, I am trying to implement something like the following code in Python:
x = np.array([[1,2,3,4,5,6], [7,8,9,10,11,12]])
idx = [0,1,2,4]
x[:, idx]
The outcome of x[:, idx] would be the subset of the matrix containing all rows and only columns described in idx, i.e., [0,1,2,4].
I am currently using ndarray (as the title suggests) but I cannot find a way to subset on non-contiguous slices. For instance, you can pass ndarray, which can take a Slice with a start, stop and an index, but I cannot find a way to pass a list of columns that cannot be described using a Slice object.
For instance:
#[macro_use]
extern crate ndarray;
fn main() {
let mut x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
let idx = vec![0, 1, 2, 4];
// The following works as expected
let y = x.slice(s![.., 0..2]);
println!("{:?}", y);
// This is conceptually what I would like to do but
// It does not work.
let y = x.slice(s![.., idx]);
}

The analogue of "advanced indexing" in Numpy is the ArrayBase::select() method:
use ndarray::{array, Axis};
fn main() {
let x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
let idx = vec![0, 1, 2, 4];
println!("{}", x.select(Axis(1), &idx));
}
producing the output
[[1, 2, 3, 5],
[7, 8, 9, 11]]
Note that the resulting array is a copy of the selected elements (just as it is in Numpy). Depending on your use case, you may not need the copy; it's possible you can make do with just iterating over idx and using x.slice(s![.., i]) for all i in idx.

Related

Return a fixed sized list based on an other list

I am looking in Kotlin for a method who return me from a list a new list with a defined number of elements (for example 10).
Whatever the size of the list, the method would always return the same number of elements.
For example, suppose a list of 3000 elements, it would return me a list of 10 elements from indexes 0, 300, 600, 900, 1200,...
Is there an extension function for this?
That's kind of a specialised thing, so there's nothing (that I know of) in the standard library - but you could easily make your own extension function:
fun <T: Any> List<T>.sample2(count: Int): List<T> {
// this allows for a fractional step, so we get a more accurate distribution of indices
// with smaller lists (where count doesn't divide into the list size evenly)
val step = size / count.toFloat()
return List(count) { i -> elementAt((i * step).toInt()) }
}
You'll get repeats if your list is too small to provide count unique indices (e.g. your list has 9 items and you want 10), so you'd have to handle that if you want different behaviour, but I think this is the easiest way to do it
Here's an idea:
Take advantage of the method chunked(size: Int), which tries to depart a given collection into sub-collections of the given size.
That's not quite what you want, but you can use it in order to implement a custom extension function which does what you want, e.g. like this:
fun List<Int>.departInto(subListCount: Int) : List<List<Int>> {
// calculate the chunk size based on the desired amount of sublists
val chunkSize = this.size / subListCount
// then apply that value to the chunked method and return the result
return this.chunked(chunkSize)
}
Using this could look as follows:
fun main() {
// define some example list (of 30 elements in this case)
val someList: List<Int> = List(30, {it})
// use the extension function
val tenSubLists = someList.departInto(10)
// print the result(s)
println(tenSubLists)
}
The output of this code will be 10 sub-lists of 3 elements (your example of 3000 elements would then result in 10 sub-lists of 300 elements each):
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]

How to find the dimensions of a (2,3 or if possible an n)dimensional slice in golang and verify if its a matrix?

For example : [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}} has dimensions [2,4].
If this is passed to a function then what is the most efficient way to find the dimension here?
Thanks
The outer dimension is just len(x) where x is the slice of slices you pass to the function (your example [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}}).
However, the inner dimensions are not guaranteed to be equal so you will have to go through each element and check what len they have.
If you have the guarantee than each element of x has the same number of elements, just find len(x[0]) if len(x) > 0.
Go only provides 1-dimensional arrays and slices. N-dimensional arrays can be emulated by using arrays of arrays, which is close to what what you're doing--you have a 1-dimensional slice, which contains 2 1-dimensional slices.
This is problematic, because slices are not of a defined length. So you could end up with slices of wildly different lengths:
[][]float64{
{1, 2, 3, 4},
{5, 6, 7, 8, 9, 10},
}
If you use actual arrays, this is simpler, because arrays have a fixed length:
[2][4]float64
You can extend this to as many dimensions as you want:
[2][4][8]float64 provides three dimensions, with respective depths of 2, 4, and 8.
Then you can tell the capacity of each dimension by using the built-in len() function on any of the elements:
foo := [2][4][7]float64{}
x := len(foo) // x == 2
y := len(foo[0]) // y == 4
z := len(foo[0][0]) // z == 8

Difference between Lists

You are given 2 lists, the first with a elements and the second with b elements, with a < b.
For each element e in list a, you want to take a element f in list b, and replace e with e-f. You cannot use a element twice unless it appears in list b twice.
The problem is to find the minimum value of the largest element of list a.
For example, say list a is [1, 2, 3, 4], and list b is [5, 6, 7, 8, 9, 10, 11, 12]. We would take the e's to be 5, 6, 7, 8, so that list a becomes [5-1, 6-2, 7-3, 8-4], with the largest element being 4. So 4 is the answer.
Another example: if list a is [1, 4, 7] and list b is [-1, 3, 4, 5, 6, 7, 8], we would take the e's to be -1, 4, 7, so that list a becomes [2, 0, 0], and the answer is 2. So 2 is the answer.
I know this is poorly worded, if I could do anything to better word it, please let me know. I tried first sorting list a and list b, then did not know what to do.
If you could help, please do.
Thanks!
calculate the values of the list:
(java)
List listA = ...;
List listb = ...;
for(int i = 0; i < listA.size(); i++){
listA.set(i, listA.get(i) - listb.get(i));
}
find the highest value in listA:
iHighestValue = listA.get(0); //setting it to 0 would not work with lists containing only negative integers
for(int j = 1; j < listA.size(); j++){
if(listA.get(j) > iHighestValue)
iHighestValue = listA.get(i);
}
[Edit]: sorry, it doesn't show as code (don't know why)

For Loop in Apple Swift

Apple's newly released language Swift has an example on the official documentation. Example is like this;
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This is pretty simple but as an extra exercise,it requires to add another variable in order to return what type is the largest number (i.e. Square is the case here)
However, I can't seem to figure out what is "(kind,numbers)" here represent and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.
Thank you all for your help in advance
Swift allows you to loop over a dictionary with tuple-syntax (key, value). So in every iteration of the for-loop Swift cares about reassigning the specified tuple-variables (kind and number in your case) to the actual dictionary-record.
To figure out which Key includes the highest number in your example you can extend your code as follows:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKey = kind
}
}
}
largest // =25
largestKey // ="Square"
Or if you want to practice the tuple-syntax try that (with the same result):
var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
(largestKey, largest) = (kind, number)
}
}
}
largest // =25
largestKey // ="Square"
I can't seem to figure out what is "(kind,numbers)" here represents
It's a key-value pair (a tuple) containing the kind of the number. This syntax is called decomposition, basically, inside the loop you can access kind as the kind and numbers as the numbers that map for it.
For example, in some iteration:
kind // "Prime"
numbers // [2, 3, 5, 7, 11, 13]
Quoting the guide:
You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within in the body of the for-in loop.
for (kind, numbers) in interestingNumbers{}
This for loop actually enumerating the key/value pairs of dictionary interestingNumbers. Where kind is the key and numbers is the correspoding value
kind:Prime //Key
numbers: [2, 3, 5, 7, 11, 13] //Value
Here the complete solution of the exercise
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var type: String = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
type = kind
}
}
}
largest
type
However, I can't seem to figure out what is "(kind,numbers)" here represent
The loop iterates over the dictionary, and every iteration gives you a key and associated value. Those are called kind (key) and numbers (value) here. You can choose any name you want.
and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.
You get each key in turn in the kind loop variable.
Once you find one that results in a new largest, you can assign that to a result variable, say largestKind.
At the end of the loop, largestKind will contain the key of the array with the largest number (that number being the largest you already have).
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This will return pair of (String,Int) which we have in Our Dictionary
similar to function return multiple value as below,
func refreshWebPage() -> (status:String,code:Int){
//refresh logic
return ("Success",200)
}

Store unevaluted function in list mathematica

Example:
list:={ Plus[1,1], Times[2,3] }
When looking at list, I get
{2,6}
I want to keep them unevaluated (as above) so that list returns
{ Plus[1,1], Times[2,3] }
Later I want to evaluate the functions in list sequence to get
{2,6}
The number of unevaluated functions in list is not known beforehand. Besides Plus, user defined functions like f[x_] may be stored in list
I hope the example is clear.
What is the best way to do this?
The best way is to store them in Hold, not List, like so:
In[255]:= f[x_] := x^2;
lh = Hold[Plus[1, 1], Times[2, 3], f[2]]
Out[256]= Hold[1 + 1, 2 3, f[2]]
In this way, you have full control over them. At some point, you may call ReleaseHold to evaluate them:
In[258]:= ReleaseHold#lh
Out[258]= Sequence[2, 6, 4]
If you want the results in a list rather than Sequence, you may use just List##lh instead. If you need to evaluate a specific one, simply use Part to extract it:
In[261]:= lh[[2]]
Out[261]= 6
If you insist on your construction, here is a way:
In[263]:= l:={Plus[1,1],Times[2,3],f[2]};
Hold[l]/.OwnValues[l]
Out[264]= Hold[{1+1,2 3,f[2]}]
EDIT
In case you have some functions/symbols with UpValues which can evaluate even inside Hold, you may want to use HoldComplete in place of Hold.
EDIT2
As pointed by #Mr.Wizard in another answer, sometimes you may find it more convenient to have Hold wrapped around individual items in your sequence. My comment here is that the usefulness of both forms is amplified once we realize that it is very easy to transform one into another and back. The following function will split the sequence inside Hold into a list of held items:
splitHeldSequence[Hold[seq___], f_: Hold] := List ## Map[f, Hold[seq]]
for example,
In[274]:= splitHeldSequence[Hold[1 + 1, 2 + 2]]
Out[274]= {Hold[1 + 1], Hold[2 + 2]}
grouping them back into a single Hold is even easier - just Apply Join:
In[275]:= Join ## {Hold[1 + 1], Hold[2 + 2]}
Out[275]= Hold[1 + 1, 2 + 2]
The two different forms are useful in diferrent circumstances. You can easily use things such as Union, Select, Cases on a list of held items without thinking much about evaluation. Once finished, you can combine them back into a single Hold, for example, to feed as unevaluated sequence of arguments to some function.
EDIT 3
Per request of #ndroock1, here is a specific example. The setup:
l = {1, 1, 1, 2, 4, 8, 3, 9, 27}
S[n_] := Module[{}, l[[n]] = l[[n]] + 1; l]
Z[n_] := Module[{}, l[[n]] = 0; l]
placing functions in Hold:
In[43]:= held = Hold[Z[1], S[1]]
Out[43]= Hold[Z[1], S[1]]
Here is how the exec function may look:
exec[n_] := MapAt[Evaluate, held, n]
Now,
In[46]:= {exec[1], exec[2]}
Out[46]= {Hold[{0, 1, 1, 2, 4, 8, 3, 9, 27}, S[1]], Hold[Z[1], {1, 1, 1, 2, 4, 8, 3, 9, 27}]}
Note that the original variable held remains unchanged, since we operate on the copy. Note also that the original setup contains mutable state (l), which is not very idiomatic in Mathematica. In particular, the order of evaluations matter:
In[61]:= Reverse[{exec[2], exec[1]}]
Out[61]= {Hold[{0, 1, 1, 2, 4, 8, 3, 9, 27}, S[1]], Hold[Z[1], {2, 1, 1, 2, 4, 8, 3, 9, 27}]}
Whether or not this is desired depends on the specific needs, I just wanted to point this out. Also, while the exec above is implemented according to the requested spec, it implicitly depends on a global variable l, which I consider a bad practice.
An alternative way to store functions suggested by #Mr.Wizard can be achieved e.g. like
In[63]:= listOfHeld = splitHeldSequence[held]
Out[63]= {Hold[Z1], Hold[S1]}
and here
In[64]:= execAlt[n_] := MapAt[ReleaseHold, listOfHeld, n]
In[70]:= l = {1, 1, 1, 2, 4, 8, 3, 9, 27} ;
{execAlt[1], execAlt[2]}
Out[71]= {{{0, 1, 1, 2, 4, 8, 3, 9, 27}, Hold[S[1]]}, {Hold[Z[1]], {1, 1, 1, 2, 4, 8, 3, 9, 27}}}
The same comments about mutability and dependence on a global variable go here as well. This last form is also more suited to query the function type:
getType[n_, lh_] := lh[[n]] /. {Hold[_Z] :> zType, Hold[_S] :> sType, _ :> unknownType}
for example:
In[172]:= getType[#, listOfHeld] & /# {1, 2}
Out[172]= {zType, sType}
The first thing that spings to mind is to not use List but rather use something like this:
SetAttributes[lst, HoldAll];
heldL=lst[Plus[1, 1], Times[2, 3]]
There will surely be lots of more erudite suggestions though!
You can also use Hold on every element that you want held:
a = {Hold[2 + 2], Hold[2*3]}
You can use HoldForm on either the elements or the list, if you want the appearance of the list without Hold visible:
b = {HoldForm[2 + 2], HoldForm[2*3]}
c = HoldForm#{2 + 2, 2*3}
{2 + 2, 2 * 3}
And you can recover the evaluated form with ReleaseHold:
a // ReleaseHold
b // ReleaseHold
c // ReleaseHold
Out[8]= {4, 6}
Out[9]= {4, 6}
Out[10]= {4, 6}
The form Hold[2+2, 2*3] or that of a and b above are good because you can easily add terms with e.g. Append. For b type is it logically:
Append[b, HoldForm[8/4]]
For Hold[2+2, 2*3]:
Hold[2+2, 2*3] ~Join~ Hold[8/4]
Another way:
lh = Function[u, Hold#u, {HoldAll, Listable}];
k = lh#{2 + 2, Sin[Pi]}
(*
->{Hold[2 + 2], Hold[Sin[\[Pi]]]}
*)
ReleaseHold#First#k
(*
-> 4
*)

Resources