Merge pull request #227 from adrianVmariano/master

subindex speed improvement
This commit is contained in:
Revar Desmera 2020-08-02 09:22:34 -07:00 committed by GitHub
commit 59aebd33ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 15 deletions

View file

@ -1172,25 +1172,25 @@ function add_scalar(v,s) =
// Function: subindex() // Function: subindex()
// Usage:
// subindex(M, idx)
// Description: // Description:
// For each array item, return the indexed subitem. // Extracts the entries listed in idx from each entry in M. For a matrix this means
// Returns a list of the values of each vector at the specfied // selecting a specified set of columsn. If idx is a number the return is a vector, otherwise
// index list or range. If the index list or range has // it is a list of lists (the submatrix).
// only one entry the output list is flattened.
// Arguments: // Arguments:
// v = The given list of lists. // M = The given list of lists.
// idx = The index, list of indices, or range of indices to fetch. // idx = The index, list of indices, or range of indices to fetch.
// Example: // Example:
// v = [[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; // M = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];
// subindex(v,2); // Returns [3, 7, 11, 15] // subindex(M,2); // Returns [3, 7, 11, 15]
// subindex(v,[2,1]); // Returns [[3, 2], [7, 6], [11, 10], [15, 14]] // subindex(M,[2]); // Returns [[3], [7], [11], [15]]
// subindex(v,[1:3]); // Returns [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16]] // subindex(M,[2,1]); // Returns [[3, 2], [7, 6], [11, 10], [15, 14]]
function subindex(v, idx) = // subindex(M,[1:3]); // Returns [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16]]
[ for(val=v) function subindex(M, idx) =
let( value=[for(i=idx) val[i]] ) is_num(idx)
len(value)==1 ? value[0] : value ? [for(row=M) row[idx]]
]; : [for(row=M) [for(i=idx) row[i]]];
// Function: zip() // Function: zip()
// Usage: // Usage:

View file

@ -358,6 +358,7 @@ test_add_scalar();
module test_subindex() { module test_subindex() {
v = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; v = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];
assert(subindex(v,2) == [3, 7, 11, 15]); assert(subindex(v,2) == [3, 7, 11, 15]);
assert(subindex(v,[2]) == [[3], [7], [11], [15]]);
assert(subindex(v,[2,1]) == [[3, 2], [7, 6], [11, 10], [15, 14]]); assert(subindex(v,[2,1]) == [[3, 2], [7, 6], [11, 10], [15, 14]]);
assert(subindex(v,[1:3]) == [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16]]); assert(subindex(v,[1:3]) == [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16]]);
} }