Indexing

Introduction

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.

Available characters

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.

:
It separates starting index and stopping one. 1:2
,
It is the dimension separator.

Examples

A default 4x4 matrix will be used for demos.

use SciPhp\NumPhp as np;

$m np::linspace(11616)->reshape(44);

echo 
"m\n$m";
m
[[1   2   3   4 ]
 [5   6   7   8 ]
 [9   10  11  12]
 [13  14  15  16]]

Example #1: Extracting vectors

$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]

Example #2: Extract 2 last columns.

$columns $m[':, -2:'];

echo 
"columns\n$columns";

The above example will output:

columns
[[3   4 ]
 [7   8 ]
 [11  12]
 [15  16]]

Example #3: Assign a value to an entire column.

$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]]

Example #4: Assign a value to the 4 central values.

$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]]