4 ms·
Perl can do this as well: @a = (10, 5, 9, 6, 20, 17, 1); @slice = @a[0, 1, 3, 6]; Though I've never seen this used for anything other than simple subl
by pdw 14y ago
Perl can do this as well:
@a = (10, 5, 9, 6, 20, 17, 1);
@slice = @a[0, 1, 3, 6];
Though I've never seen this used for anything other than simple sublists (like @a[0..3]).
- disgruntledphd2 14y agoI use this kind of stuff in R all the time. Its actually wonderful how many typical data analytic tasks can be expressed in this format. Thats why, I suspect, both R and J have this operator.
- tzs 14y agoI've used something like that: @state[1,2,3,5,6,7,9,10,11,13,14,15] = @state[5,10,15,9,14,3,13,2,7,1,6,11]; That's the row shift transformation in AES encryption.
- no_flags 14y agoSo can MATLAB. a = [10 5 9 6 20 7]; slice = a([1 2 4 7]); I guess it's not called matrix laboratory for nothing.
- roguecoder 14y agoplus, MATLAB has "find", which returns a list of all the positions of a matrix matching some pattern. The combination of the two makes things that are very ugly to express in other languages quite pretty. Too bad it's wicked expensive, proprietary and slow. I quite enjoy the paradigm.
- blt 14y agoThe obscure matrix language IDL has this too via WHERE. It's really nice. This syntax is essential for image processing unless you want to write a bunch of unnecessary for loops. img[WHERE(img LT 5)] = 0 I built a bunch of sparse image processing algorithms using index lists. Pass in the indices and the values at those locations. Everything else is assumed zero. Sort the index array and you can use binary search to look up neighbors. On my domain images which were less than 2% foreground it made a big difference.
- EvilTerran 14y agoI've used perl's array slices as @array[@indices] in the past. Can't remember why, but I have. It also works for hashes: %hash = (foo => "bar", one => "two", alpha => "beta"); @keys = ('alpha', 'one'); @hash{@keys} == ('beta', 'two');
- sparky_z 14y agoAn array slice can also be used as an lvalue in an assignment: @a = (10, 5, 9, 6, 17, 1); @a[3,5,1] = qw(yes no maybe); print "@a"; >> "10 maybe 9 yes 17 no" In fact, because the slice can be both an lvalue and an rvalue, this is an easy way to transpose elements in-place. @a = (10, 5, 9, 6, 17, 1); @a[0,4] = @a[4,0]; print "@a"; >> "17, 5, 9, 6, 10, 1";