Slicing and indexing are elegant ways to access and affect some
subsets of a matrix. In PHP, it is not a native capability,
therefore,
NdArrays can be indexed using a string such as
':, -1'
(last column) or
'-1'
(last line).
An interesting property of indexes is to have a scalar key
to address a multidimensional array.
For example, in PHP, accessing a three levels array would seem like
$m[0][0][0]
.
With indexes, it would be
$m['0,0,0']
.
Several ways of using indexes are outlined below.
integers
A single integer points to one row or one col.
2 integers separated by a
:
points
to a range of rows or columns.
Matrix are indexed from 0 to n - 1.
:
1:2
,
A default 4x4 matrix will be used for demos.
use SciPhp\NumPhp as np;
$m = np::linspace(1, 16, 16)->reshape(4, 4);
echo "m\n$m";
m [[1 2 3 4 ] [5 6 7 8 ] [9 10 11 12] [13 14 15 16]]
$row = $m['1'];
$column = $m[':,1'];
echo "row\n$row", "column\n$column";
The above example will output:
row [5 6 7 8] column [2 6 10 14]
$columns = $m[':, -2:'];
echo "columns\n$columns";
The above example will output:
columns [[3 4 ] [7 8 ] [11 12] [15 16]]
$m[':, 1'] = 42;
echo "m\n$m";
The above example will output:
m [[1 42 3 4 ] [5 42 7 8 ] [9 42 11 12] [13 42 15 16]]
$m['1:2, 1:2'] = 0;
echo "m\n$m";
The above example will output:
m [[1 2 3 4 ] [5 0 0 8 ] [9 0 0 12] [13 14 15 16]]