File: Advanced-Indexing.html

package info (click to toggle)
octave 10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 145,388 kB
  • sloc: cpp: 335,976; ansic: 82,241; fortran: 20,963; objc: 9,402; sh: 8,756; yacc: 4,392; lex: 4,333; perl: 1,544; java: 1,366; awk: 1,259; makefile: 659; xml: 192
file content (395 lines) | stat: -rw-r--r-- 18,373 bytes parent folder | download | duplicates (2)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<!DOCTYPE html>
<html>
<!-- Created by GNU Texinfo 7.1.1, https://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Advanced Indexing (GNU Octave (version 10.3.0))</title>

<meta name="description" content="Advanced Indexing (GNU Octave (version 10.3.0))">
<meta name="keywords" content="Advanced Indexing (GNU Octave (version 10.3.0))">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="index.html" rel="start" title="Top">
<link href="Concept-Index.html" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Index-Expressions.html" rel="up" title="Index Expressions">
<style type="text/css">
<!--
a.copiable-link {visibility: hidden; text-decoration: none; line-height: 0em}
div.example {margin-left: 3.2em}
span:hover a.copiable-link {visibility: visible}
strong.def-name {font-family: monospace; font-weight: bold; font-size: larger}
-->
</style>
<link rel="stylesheet" type="text/css" href="octave.css">


</head>

<body lang="en">
<div class="subsection-level-extent" id="Advanced-Indexing">
<div class="nav-panel">
<p>
Up: <a href="Index-Expressions.html" accesskey="u" rel="up">Index Expressions</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<h4 class="subsection" id="Advanced-Indexing-1"><span>8.1.1 Advanced Indexing<a class="copiable-link" href="#Advanced-Indexing-1"> &para;</a></span></h4>

<h4 class="subsubheading" id="Chained-indexing"><span>Chained indexing<a class="copiable-link" href="#Chained-indexing"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Chained-indexing"></a>
<p>Octave permits the use of repeated (chained) index expressions to extract
subsets of an array in a single command without the need to use intermediate
variables.  This can make it easier to write code with either complicated
indexing operations or using multiple indexing methods.  The following example
shows two equivalent index extraction operations:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">A = reshape (1:16, 4, 4);
B = A(2:4, 2:3);
C = B(3:5);
D = C( [ true, false, true ] )
     &rArr; D = [ 8, 11 ]

D = A(2:4, 2:3)(3:5)([ true, false, true ])
     &rArr; D = [ 8, 11 ]
</pre></div></div>

<p>Chained indexing will necessarily be slower than a single index expression
producing the same results, but is usually more computationally efficient
than performing multiple discrete indexing operations with intermediate
variable assignments.
</p>
<p>Note that chained indexing is only compatible with right-hand expressions and
can not be used on the left-hand side of assignment operations.
</p>
<h4 class="subsubheading" id="Component-to-linear-index-conversion"><span>Component to linear index conversion<a class="copiable-link" href="#Component-to-linear-index-conversion"> &para;</a></span></h4>
<p>When it is necessary to extract subsets of entries out of an array whose
indices cannot be written as a Cartesian product of components, linear
indexing together with the function <code class="code">sub2ind</code> can be used.  For example:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">A = reshape (1:8, 2, 2, 2)  # Create 3-D array
A =

ans(:,:,1) =

   1   3
   2   4

ans(:,:,2) =

   5   7
   6   8

A(sub2ind (size (A), [1, 2, 1], [1, 1, 2], [1, 2, 1]))
   &rArr; ans = [A(1, 1, 1), A(2, 1, 2), A(1, 2, 1)]
</pre></div></div>

<a class="anchor" id="XREFsub2ind"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-sub2ind"><span><code class="def-type"><var class="var">ind</var> =</code> <strong class="def-name">sub2ind</strong> <code class="def-code-arguments">(<var class="var">dims</var>, <var class="var">i</var>, <var class="var">j</var>)</code><a class="copiable-link" href="#index-sub2ind"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-sub2ind-1"><span><code class="def-type"><var class="var">ind</var> =</code> <strong class="def-name">sub2ind</strong> <code class="def-code-arguments">(<var class="var">dims</var>, <var class="var">s1</var>, <var class="var">s2</var>, &hellip;, <var class="var">sN</var>)</code><a class="copiable-link" href="#index-sub2ind-1"> &para;</a></span></dt>
<dd><p>Convert subscripts to linear indices.
</p>
<p>The input <var class="var">dims</var> is a dimension vector where each element is the size of
the array in the respective dimension (see <a class="pxref" href="Object-Sizes.html#XREFsize"><code class="code">size</code></a>).  The
remaining inputs are scalars or vectors of subscripts to be converted.
</p>
<p>The output vector <var class="var">ind</var> contains the converted linear indices.
</p>
<p>Background: Array elements can be specified either by a linear index which
starts at 1 and runs through the number of elements in the array, or they may
be specified with subscripts for the row, column, page, etc.  The functions
<code class="code">ind2sub</code> and <code class="code">sub2ind</code> interconvert between the two forms.
</p>
<p>The linear index traverses dimension 1 (rows), then dimension 2 (columns), then
dimension 3 (pages), etc. until it has numbered all of the elements.
Consider the following 3-by-3 matrices:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">[(1,1), (1,2), (1,3)]     [1, 4, 7]
[(2,1), (2,2), (2,3)] ==&gt; [2, 5, 8]
[(3,1), (3,2), (3,3)]     [3, 6, 9]
</pre></div></div>

<p>The left matrix contains the subscript tuples for each matrix element.  The
right matrix shows the linear indices for the same matrix.
</p>
<p>The following example shows how to convert the two-dimensional indices
<code class="code">(2,1)</code> and <code class="code">(2,3)</code> of a 3-by-3 matrix to linear indices with a
single call to <code class="code">sub2ind</code>.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">s1 = [2, 2];
s2 = [1, 3];
ind = sub2ind ([3, 3], s1, s2)
    &rArr; ind =  2   8
</pre></div></div>

<p><strong class="strong">See also:</strong> <a class="ref" href="#XREFind2sub">ind2sub</a>, <a class="ref" href="Object-Sizes.html#XREFsize">size</a>.
</p></dd></dl>


<a class="anchor" id="XREFind2sub"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-ind2sub"><span><code class="def-type">[<var class="var">s1</var>, <var class="var">s2</var>, &hellip;, <var class="var">sN</var>] =</code> <strong class="def-name">ind2sub</strong> <code class="def-code-arguments">(<var class="var">dims</var>, <var class="var">ind</var>)</code><a class="copiable-link" href="#index-ind2sub"> &para;</a></span></dt>
<dd><p>Convert linear indices to subscripts.
</p>
<p>The input <var class="var">dims</var> is a dimension vector where each element is the size of
the array in the respective dimension (see <a class="pxref" href="Object-Sizes.html#XREFsize"><code class="code">size</code></a>).  The
second input <var class="var">ind</var> contains linear indices to be converted.
</p>
<p>The outputs <var class="var">s1</var>, &hellip;, <var class="var">sN</var> contain the converted subscripts.
</p>
<p>Background: Array elements can be specified either by a linear index which
starts at 1 and runs through the number of elements in the array, or they may
be specified with subscripts for the row, column, page, etc.  The functions
<code class="code">ind2sub</code> and <code class="code">sub2ind</code> interconvert between the two forms.
</p>
<p>The linear index traverses dimension 1 (rows), then dimension 2 (columns), then
dimension 3 (pages), etc. until it has numbered all of the elements.
Consider the following 3-by-3 matrices:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">[1, 4, 7]     [(1,1), (1,2), (1,3)]
[2, 5, 8] ==&gt; [(2,1), (2,2), (2,3)]
[3, 6, 9]     [(3,1), (3,2), (3,3)]
</pre></div></div>

<p>The left matrix contains the linear indices for each matrix element.  The right
matrix shows the subscript tuples for the same matrix.
</p>
<p>The following example shows how to convert the linear indices <code class="code">2</code> and
<code class="code">8</code> to appropriate subscripts of a 3-by-3 matrix.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">ind = [2, 8];
[r, c] = ind2sub ([3, 3], ind)
    &rArr; r =  2   2
    &rArr; c =  1   3
</pre></div></div>

<p>If the number of output subscripts exceeds the number of dimensions, the
exceeded dimensions are set to <code class="code">1</code>.  On the other hand, if fewer
subscripts than dimensions are provided, the exceeding dimensions are merged
into the final requested dimension.  For clarity, consider the following
examples:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">ind  = [2, 8];
dims = [3, 3];
## same as dims = [3, 3, 1]
[r, c, s] = ind2sub (dims, ind)
    &rArr; r =  2   2
    &rArr; c =  1   3
    &rArr; s =  1   1
## same as dims = [9]
r = ind2sub (dims, ind)
    &rArr; r =  2   8
</pre></div></div>

<p><strong class="strong">See also:</strong> <a class="ref" href="#XREFsub2ind">sub2ind</a>, <a class="ref" href="Object-Sizes.html#XREFsize">size</a>.
</p></dd></dl>


<a class="anchor" id="XREFisindex"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-isindex"><span><code class="def-type"><var class="var">tf</var> =</code> <strong class="def-name">isindex</strong> <code class="def-code-arguments">(<var class="var">ind</var>)</code><a class="copiable-link" href="#index-isindex"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-isindex-1"><span><code class="def-type"><var class="var">tf</var> =</code> <strong class="def-name">isindex</strong> <code class="def-code-arguments">(<var class="var">ind</var>, <var class="var">n</var>)</code><a class="copiable-link" href="#index-isindex-1"> &para;</a></span></dt>
<dd><p>Return true if <var class="var">ind</var> is a valid index.
</p>
<p>Valid indices are either positive integers (although possibly of real data
type), or logical arrays.
</p>
<p>If present, <var class="var">n</var> specifies the maximum extent of the dimension to be
indexed.  When possible the internal result is cached so that subsequent
indexing using <var class="var">ind</var> will not perform the check again.
</p>
<p>Implementation Note: Strings are first converted to double values before the
checks for valid indices are made.  Unless a string contains the NULL
character &quot;\0&quot;, it will always be a valid index.
</p></dd></dl>


<h4 class="subsubheading" id="Component-count-not-equal-to-dimensionality"><span>Component count not equal to dimensionality<a class="copiable-link" href="#Component-count-not-equal-to-dimensionality"> &para;</a></span></h4>
<p>An array with &lsquo;<samp class="samp">nd</samp>&rsquo; dimensions can be indexed by an index expression which
has from 1 to &lsquo;<samp class="samp">nd</samp>&rsquo; components.  For the ordinary and most common case, the
number of components &lsquo;<samp class="samp">M</samp>&rsquo; matches the number of dimensions &lsquo;<samp class="samp">nd</samp>&rsquo;.  In
this case the ordinary indexing rules apply and each component corresponds to
the respective dimension of the array.
</p>
<p>However, if the number of indexing components exceeds the number of dimensions
(<code class="code">M&nbsp;&gt;&nbsp;nd</code><!-- /@w -->) then the excess components must all be singletons
(<code class="code">1</code>).  Moreover, if <code class="code">M&nbsp;&lt;&nbsp;nd</code><!-- /@w -->, the behavior is equivalent to
reshaping the input object so as to merge the trailing
<code class="code">nd&nbsp;-&nbsp;M</code><!-- /@w -->&nbsp;dimensions into the last index dimension <code class="code">M</code>.  Thus,
the result will have the dimensionality of the index expression, and not the
original object.  This is the case whenever dimensionality of the index is
greater than one (<code class="code">M&nbsp;&gt;&nbsp;1</code><!-- /@w -->), so that the special rules for linear
indexing are not applied.  This is easiest to understand with an example:
</p>
<div class="example smallexample">
<pre class="example-preformatted">A = reshape (1:8, 2, 2, 2)  # Create 3-D array
A =

ans(:,:,1) =

   1   3
   2   4

ans(:,:,2) =

   5   7
   6   8

## 2-D indexing causes third dimension to be merged into second dimension.
## Equivalent array for indexing, Atmp, is now 2x4.
Atmp = reshape (A, 2, 4)
Atmp =

   1   3   5   7
   2   4   6   8


A(2,1)   # Reshape to 2x4 matrix, second entry of first column: ans = 2
A(2,4)   # Reshape to 2x4 matrix, second entry of fourth column: ans = 8
A(:,:)   # Reshape to 2x4 matrix, select all rows &amp; columns, ans = Atmp
</pre></div>

<p>Note here the elegant use of the double colon to replace the call to the
<code class="code">reshape</code> function.
</p>
<h4 class="subsubheading" id="Array-replication"><span>Array replication<a class="copiable-link" href="#Array-replication"> &para;</a></span></h4>
<p>Another advanced use of linear indexing is to create arrays filled with a
single value.  This can be done by using an index of ones on a scalar value.
The result is an object with the dimensions of the index expression and every
element equal to the original scalar.  For example, the following statements
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">a = 13;
a(ones (1, 4))
</pre></div></div>

<p>produce a row vector whose four elements are all equal to 13.
</p>
<p>Similarly, by indexing a scalar with two vectors of ones it is possible to
create a matrix.  The following statements
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">a = 13;
a(ones (1, 2), ones (1, 3))
</pre></div></div>

<p>create a 2x3 matrix with all elements equal to 13.  This could also have been
written as
</p>
<div class="example">
<pre class="example-preformatted">13(ones (2, 3))
</pre></div>

<p>It is more efficient to use indexing rather than the code construction
<code class="code">scalar * ones (M, N, &hellip;)</code> because it avoids the unnecessary
multiplication operation.  Moreover, multiplication may not be defined for the
object to be replicated whereas indexing an array is always defined.  The
following code shows how to create a 2x3 cell array from a base unit which is
not itself a scalar.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">{&quot;Hello&quot;}(ones (2, 3))
</pre></div></div>

<p>It should be noted that <code class="code">ones (1, n)</code> (a row vector of ones) results in a
range object (with zero increment).  A range is stored internally as a starting
value, increment, end value, and total number of values; hence, it is more
efficient for storage than a vector or matrix of ones whenever the number of
elements is greater than 4.  In particular, when &lsquo;<samp class="samp">r</samp>&rsquo; is a row vector, the
expressions
</p>
<div class="example">
<pre class="example-preformatted">  r(ones (1, n), :)
</pre></div>

<div class="example">
<pre class="example-preformatted">  r(ones (n, 1), :)
</pre></div>

<p>will produce identical results, but the first one will be significantly faster,
at least for &lsquo;<samp class="samp">r</samp>&rsquo; and &lsquo;<samp class="samp">n</samp>&rsquo; large enough.  In the first case the index
is held in compressed form as a range which allows Octave to choose a more
efficient algorithm to handle the expression.
</p>
<p>A general recommendation for users unfamiliar with these techniques is to use
the function <code class="code">repmat</code> for replicating smaller arrays into bigger ones,
which uses such tricks.
</p>
<h4 class="subsubheading" id="Indexing-for-performance-enhancement"><span>Indexing for performance enhancement<a class="copiable-link" href="#Indexing-for-performance-enhancement"> &para;</a></span></h4>
<p>A second use of indexing is to speed up code.  Indexing is a fast operation
and judicious use of it can reduce the requirement for looping over individual
array elements, which is a slow operation.
</p>
<p>Consider the following example which creates a 10-element row vector
<em class="math">a</em> containing the values
a(i) = sqrt (i).
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">for i = 1:10
  a(i) = sqrt (i);
endfor
</pre></div></div>

<p>It is quite inefficient to create a vector using a loop like this.  In this
case, it would have been much more efficient to use the expression
</p>
<div class="example">
<pre class="example-preformatted">a = sqrt (1:10);
</pre></div>

<p>which avoids the loop entirely.
</p>
<p>In cases where a loop cannot be avoided, or a number of values must be combined
to form a larger matrix, it is generally faster to set the size of the matrix
first (pre-allocate storage), and then insert elements using indexing commands.
For example, given a matrix <code class="code">a</code>,
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">[nr, nc] = size (a);
x = zeros (nr, n * nc);
for i = 1:n
  x(:,(i-1)*nc+1:i*nc) = a;
endfor
</pre></div></div>

<p>is considerably faster than
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">x = a;
for i = 1:n-1
  x = [x, a];
endfor
</pre></div></div>

<p>because Octave does not have to repeatedly resize the intermediate result.
</p>
<p>For more performance improvement suggestions see
<a class="ref" href="Vectorization-and-Faster-Code-Execution.html">Vectorization and Faster Code Execution</a>.
</p>
</div>
<hr>
<div class="nav-panel">
<p>
Up: <a href="Index-Expressions.html">Index Expressions</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html" title="Index" rel="index">Index</a>]</p>
</div>



</body>
</html>