284 lines
61 KiB
HTML
284 lines
61 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Multi-dimensional Arrays · The Julia Language</title><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||
|
||
ga('create', 'UA-28835595-6', 'auto');
|
||
ga('send', 'pageview');
|
||
</script><link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet" type="text/css"/><link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"/><script>documenterBaseURL=".."</script><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" data-main="../assets/documenter.js"></script><script src="../siteinfo.js"></script><script src="../../versions.js"></script><link href="../assets/highlightjs/default.css" rel="stylesheet" type="text/css"/><link href="../assets/documenter.css" rel="stylesheet" type="text/css"/></head><body><nav class="toc"><a href="../index.html"><img class="logo" src="../assets/logo.png" alt="The Julia Language logo"/></a><h1>The Julia Language</h1><select id="version-selector" onChange="window.location.href=this.value" style="visibility: hidden"></select><form class="search" action="../search.html"><input id="search-query" name="q" type="text" placeholder="Search docs"/></form><ul><li><a class="toctext" href="../index.html">Home</a></li><li><span class="toctext">Manual</span><ul><li><a class="toctext" href="introduction.html">Introduction</a></li><li><a class="toctext" href="getting-started.html">Getting Started</a></li><li><a class="toctext" href="variables.html">Variables</a></li><li><a class="toctext" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a></li><li><a class="toctext" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a></li><li><a class="toctext" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a></li><li><a class="toctext" href="strings.html">Strings</a></li><li><a class="toctext" href="functions.html">Functions</a></li><li><a class="toctext" href="control-flow.html">Control Flow</a></li><li><a class="toctext" href="variables-and-scoping.html">Scope of Variables</a></li><li><a class="toctext" href="types.html">Types</a></li><li><a class="toctext" href="methods.html">Methods</a></li><li><a class="toctext" href="constructors.html">Constructors</a></li><li><a class="toctext" href="conversion-and-promotion.html">Conversion and Promotion</a></li><li><a class="toctext" href="interfaces.html">Interfaces</a></li><li><a class="toctext" href="modules.html">Modules</a></li><li><a class="toctext" href="documentation.html">Documentation</a></li><li><a class="toctext" href="metaprogramming.html">Metaprogramming</a></li><li class="current"><a class="toctext" href="arrays.html">Multi-dimensional Arrays</a><ul class="internal"><li><a class="toctext" href="#Arrays-1">Arrays</a></li><li><a class="toctext" href="#Sparse-Vectors-and-Matrices-1">Sparse Vectors and Matrices</a></li></ul></li><li><a class="toctext" href="linear-algebra.html">Linear algebra</a></li><li><a class="toctext" href="networking-and-streams.html">Networking and Streams</a></li><li><a class="toctext" href="parallel-computing.html">Parallel Computing</a></li><li><a class="toctext" href="dates.html">Date and DateTime</a></li><li><a class="toctext" href="interacting-with-julia.html">Interacting With Julia</a></li><li><a class="toctext" href="running-external-programs.html">Running External Programs</a></li><li><a class="toctext" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a></li><li><a class="toctext" href="handling-operating-system-variation.html">Handling Operating System Variation</a></li><li><a class="toctext" href="environment-variables.html">Environment Variables</a></li><li><a class="toctext" href="embedding.html">Embedding Julia</a></li><li><a class="toctext" href="packages.html">Packages</a></li><li><a class="toctext" href="profile.html">Profiling</a></li><li><a class="toctext" href="stacktraces.html">Stack Traces</a></li><li><a class="toctext" href="performance-tips.html">Performance Tips</a></li><li><a class="toctext" href="workflow-tips.html">Workflow Tips</a></li><li><a class="toctext" href="style-guide.html">Style Guide</a></li><li><a class="toctext" href="faq.html">Frequently Asked Questions</a></li><li><a class="toctext" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a></li><li><a class="toctext" href="unicode-input.html">Unicode Input</a></li></ul></li><li><span class="toctext">Standard Library</span><ul><li><a class="toctext" href="../stdlib/base.html">Essentials</a></li><li><a class="toctext" href="../stdlib/collections.html">Collections and Data Structures</a></li><li><a class="toctext" href="../stdlib/math.html">Mathematics</a></li><li><a class="toctext" href="../stdlib/numbers.html">Numbers</a></li><li><a class="toctext" href="../stdlib/strings.html">Strings</a></li><li><a class="toctext" href="../stdlib/arrays.html">Arrays</a></li><li><a class="toctext" href="../stdlib/parallel.html">Tasks and Parallel Computing</a></li><li><a class="toctext" href="../stdlib/linalg.html">Linear Algebra</a></li><li><a class="toctext" href="../stdlib/constants.html">Constants</a></li><li><a class="toctext" href="../stdlib/file.html">Filesystem</a></li><li><a class="toctext" href="../stdlib/io-network.html">I/O and Network</a></li><li><a class="toctext" href="../stdlib/punctuation.html">Punctuation</a></li><li><a class="toctext" href="../stdlib/sort.html">Sorting and Related Functions</a></li><li><a class="toctext" href="../stdlib/pkg.html">Package Manager Functions</a></li><li><a class="toctext" href="../stdlib/dates.html">Dates and Time</a></li><li><a class="toctext" href="../stdlib/iterators.html">Iteration utilities</a></li><li><a class="toctext" href="../stdlib/test.html">Unit Testing</a></li><li><a class="toctext" href="../stdlib/c.html">C Interface</a></li><li><a class="toctext" href="../stdlib/libc.html">C Standard Library</a></li><li><a class="toctext" href="../stdlib/libdl.html">Dynamic Linker</a></li><li><a class="toctext" href="../stdlib/profile.html">Profiling</a></li><li><a class="toctext" href="../stdlib/stacktraces.html">StackTraces</a></li><li><a class="toctext" href="../stdlib/simd-types.html">SIMD Support</a></li></ul></li><li><span class="toctext">Developer Documentation</span><ul><li><a class="toctext" href="../devdocs/reflection.html">Reflection and introspection</a></li><li><span class="toctext">Documentation of Julia's Internals</span><ul><li><a class="toctext" href="../devdocs/init.html">Initialization of the Julia runtime</a></li><li><a class="toctext" href="../devdocs/ast.html">Julia ASTs</a></li><li><a class="toctext" href="../devdocs/types.html">More about types</a></li><li><a class="toctext" href="../devdocs/object.html">Memory layout of Julia Objects</a></li><li><a class="toctext" href="../devdocs/eval.html">Eval of Julia code</a></li><li><a class="toctext" href="../devdocs/callconv.html">Calling Conventions</a></li><li><a class="toctext" href="../devdocs/compiler.html">High-level Overview of the Native-Code Generation Process</a></li><li><a class="toctext" href="../devdocs/functions.html">Julia Functions</a></li><li><a class="toctext" href="../devdocs/cartesian.html">Base.Cartesian</a></li><li><a class="toctext" href="../devdocs/meta.html">Talking to the compiler (the <code>:meta</code> mechanism)</a></li><li><a class="toctext" href="../devdocs/subarrays.html">SubArrays</a></li><li><a class="toctext" href="../devdocs/sysimg.html">System Image Building</a></li><li><a class="toctext" href="../devdocs/llvm.html">Working with LLVM</a></li><li><a class="toctext" href="../devdocs/stdio.html">printf() and stdio in the Julia runtime</a></li><li><a class="toctext" href="../devdocs/boundscheck.html">Bounds checking</a></li><li><a class="toctext" href="../devdocs/locks.html">Proper maintenance and care of multi-threading locks</a></li><li><a class="toctext" href="../devdocs/offset-arrays.html">Arrays with custom indices</a></li><li><a class="toctext" href="../devdocs/libgit2.html">Base.LibGit2</a></li><li><a class="toctext" href="../devdocs/require.html">Module loading</a></li></ul></li><li><span class="toctext">Developing/debugging Julia's C code</span><ul><li><a class="toctext" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li><li><a class="toctext" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li><li><a class="toctext" href="../devdocs/valgrind.html">Using Valgrind with Julia</a></li><li><a class="toctext" href="../devdocs/sanitizers.html">Sanitizer support</a></li></ul></li></ul></li></ul></nav><article id="docs"><header><nav><ul><li>Manual</li><li><a href="arrays.html">Multi-dimensional Arrays</a></li></ul><a class="edit-page" href="https://github.com/JuliaLang/julia/tree/d386e40c17d43b79fc89d3e579fc04547241787c/doc/src/manual/arrays.md"><span class="fa"></span> Edit on GitHub</a></nav><hr/><div id="topbar"><span>Multi-dimensional Arrays</span><a class="fa fa-bars" href="#"></a></div></header><h1><a class="nav-anchor" id="man-multi-dim-arrays-1" href="#man-multi-dim-arrays-1">Multi-dimensional Arrays</a></h1><p>Julia, like most technical computing languages, provides a first-class array implementation. Most technical computing languages pay a lot of attention to their array implementation at the expense of other containers. Julia does not treat arrays in any special way. The array library is implemented almost completely in Julia itself, and derives its performance from the compiler, just like any other code written in Julia. As such, it's also possible to define custom array types by inheriting from <code>AbstractArray.</code> See the <a href="interfaces.html#man-interface-array-1">manual section on the AbstractArray interface</a> for more details on implementing a custom array type.</p><p>An array is a collection of objects stored in a multi-dimensional grid. In the most general case, an array may contain objects of type <code>Any</code>. For most computational purposes, arrays should contain objects of a more specific type, such as <a href="../stdlib/numbers.html#Core.Float64"><code>Float64</code></a> or <a href="../stdlib/numbers.html#Core.Int32"><code>Int32</code></a>.</p><p>In general, unlike many other technical computing languages, Julia does not expect programs to be written in a vectorized style for performance. Julia's compiler uses type inference and generates optimized code for scalar array indexing, allowing programs to be written in a style that is convenient and readable, without sacrificing performance, and using less memory at times.</p><p>In Julia, all arguments to functions are passed by reference. Some technical computing languages pass arrays by value, and this is convenient in many cases. In Julia, modifications made to input arrays within a function will be visible in the parent function. The entire Julia array library ensures that inputs are not modified by library functions. User code, if it needs to exhibit similar behavior, should take care to create a copy of inputs that it may modify.</p><h2><a class="nav-anchor" id="Arrays-1" href="#Arrays-1">Arrays</a></h2><h3><a class="nav-anchor" id="Basic-Functions-1" href="#Basic-Functions-1">Basic Functions</a></h3><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/collections.html#Base.eltype"><code>eltype(A)</code></a></td><td>the type of the elements contained in <code>A</code></td></tr><tr><td><a href="../stdlib/collections.html#Base.length-Tuple{Any}"><code>length(A)</code></a></td><td>the number of elements in <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.ndims"><code>ndims(A)</code></a></td><td>the number of dimensions of <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.size"><code>size(A)</code></a></td><td>a tuple containing the dimensions of <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.size"><code>size(A,n)</code></a></td><td>the size of <code>A</code> along dimension <code>n</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.indices-Tuple{Any}"><code>indices(A)</code></a></td><td>a tuple containing the valid indices of <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.indices-Tuple{Any}"><code>indices(A,n)</code></a></td><td>a range expressing the valid indices along dimension <code>n</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.eachindex"><code>eachindex(A)</code></a></td><td>an efficient iterator for visiting each position in <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.stride"><code>stride(A,k)</code></a></td><td>the stride (linear index distance between adjacent elements) along dimension <code>k</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.strides"><code>strides(A)</code></a></td><td>a tuple of the strides in each dimension</td></tr></table><h3><a class="nav-anchor" id="Construction-and-Initialization-1" href="#Construction-and-Initialization-1">Construction and Initialization</a></h3><p>Many functions for constructing and initializing arrays are provided. In the following list of such functions, calls with a <code>dims...</code> argument can either take a single tuple of dimension sizes or a series of dimension sizes passed as a variable number of arguments. Most of these functions also accept a first input <code>T</code>, which is the element type of the array. If the type <code>T</code> is omitted it will default to <a href="../stdlib/numbers.html#Core.Float64"><code>Float64</code></a>.</p><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/arrays.html#Core.Array"><code>Array{T}(dims...)</code></a></td><td>an uninitialized dense <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a></td></tr><tr><td><a href="../stdlib/arrays.html#Base.zeros"><code>zeros(T, dims...)</code></a></td><td>an <code>Array</code> of all zeros</td></tr><tr><td><a href="../stdlib/arrays.html#Base.zeros"><code>zeros(A)</code></a></td><td>an array of all zeros with the same type, element type and shape as <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.ones"><code>ones(T, dims...)</code></a></td><td>an <code>Array</code> of all ones</td></tr><tr><td><a href="../stdlib/arrays.html#Base.ones"><code>ones(A)</code></a></td><td>an array of all ones with the same type, element type and shape as <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.trues"><code>trues(dims...)</code></a></td><td>a <a href="../stdlib/arrays.html#Base.BitArray"><code>BitArray</code></a> with all values <code>true</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.trues"><code>trues(A)</code></a></td><td>a <code>BitArray</code> with all values <code>true</code> and the same shape as <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.falses"><code>falses(dims...)</code></a></td><td>a <code>BitArray</code> with all values <code>false</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.falses"><code>falses(A)</code></a></td><td>a <code>BitArray</code> with all values <code>false</code> and the same shape as <code>A</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.reshape"><code>reshape(A, dims...)</code></a></td><td>an array containing the same data as <code>A</code>, but with different dimensions</td></tr><tr><td><a href="../stdlib/base.html#Base.copy"><code>copy(A)</code></a></td><td>copy <code>A</code></td></tr><tr><td><a href="../stdlib/base.html#Base.deepcopy"><code>deepcopy(A)</code></a></td><td>copy <code>A</code>, recursively copying its elements</td></tr><tr><td><a href="../stdlib/arrays.html#Base.similar-Tuple{AbstractArray}"><code>similar(A, T, dims...)</code></a></td><td>an uninitialized array of the same type as <code>A</code> (dense, sparse, etc.), but with the specified element type and dimensions. The second and third arguments are both optional, defaulting to the element type and dimensions of <code>A</code> if omitted.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.reinterpret"><code>reinterpret(T, A)</code></a></td><td>an array with the same binary data as <code>A</code>, but with element type <code>T</code></td></tr><tr><td><a href="../stdlib/numbers.html#Base.Random.rand"><code>rand(T, dims...)</code></a></td><td>an <code>Array</code> with random, iid <a href="#footnote-1">[1]</a> and uniformly distributed values in the half-open interval <span>$[0, 1)$</span></td></tr><tr><td><a href="../stdlib/numbers.html#Base.Random.randn"><code>randn(T, dims...)</code></a></td><td>an <code>Array</code> with random, iid and standard normally distributed values</td></tr><tr><td><a href="../stdlib/arrays.html#Base.eye"><code>eye(T, n)</code></a></td><td><code>n</code>-by-<code>n</code> identity matrix</td></tr><tr><td><a href="../stdlib/arrays.html#Base.eye"><code>eye(T, m, n)</code></a></td><td><code>m</code>-by-<code>n</code> identity matrix</td></tr><tr><td><a href="../stdlib/arrays.html#Base.linspace"><code>linspace(start, stop, n)</code></a></td><td>range of <code>n</code> linearly spaced elements from <code>start</code> to <code>stop</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.fill!"><code>fill!(A, x)</code></a></td><td>fill the array <code>A</code> with the value <code>x</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.fill"><code>fill(x, dims...)</code></a></td><td>an <code>Array</code> filled with the value <code>x</code></td></tr></table><div class="footnote" id="footnote-1"><a href="#footnote-1"><strong>[1]</strong></a><p><em>iid</em>, independently and identically distributed.</p></div><p>The syntax <code>[A, B, C, ...]</code> constructs a 1-d array (vector) of its arguments. If all arguments have a common <a href="conversion-and-promotion.html#conversion-and-promotion-1">promotion type</a> then they get converted to that type using <code>convert()</code>.</p><h3><a class="nav-anchor" id="Concatenation-1" href="#Concatenation-1">Concatenation</a></h3><p>Arrays can be constructed and also concatenated using the following functions:</p><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/arrays.html#Base.cat"><code>cat(k, A...)</code></a></td><td>concatenate input n-d arrays along the dimension <code>k</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.vcat"><code>vcat(A...)</code></a></td><td>shorthand for <code>cat(1, A...)</code></td></tr><tr><td><a href="../stdlib/arrays.html#Base.hcat"><code>hcat(A...)</code></a></td><td>shorthand for <code>cat(2, A...)</code></td></tr></table><p>Scalar values passed to these functions are treated as 1-element arrays.</p><p>The concatenation functions are used so often that they have special syntax:</p><table><tr><th>Expression</th><th>Calls</th></tr><tr><td><code>[A; B; C; ...]</code></td><td><a href="../stdlib/arrays.html#Base.vcat"><code>vcat()</code></a></td></tr><tr><td><code>[A B C ...]</code></td><td><a href="../stdlib/arrays.html#Base.hcat"><code>hcat()</code></a></td></tr><tr><td><code>[A B; C D; ...]</code></td><td><a href="../stdlib/arrays.html#Base.hvcat"><code>hvcat()</code></a></td></tr></table><p><a href="../stdlib/arrays.html#Base.hvcat"><code>hvcat()</code></a> concatenates in both dimension 1 (with semicolons) and dimension 2 (with spaces).</p><h3><a class="nav-anchor" id="Typed-array-initializers-1" href="#Typed-array-initializers-1">Typed array initializers</a></h3><p>An array with a specific element type can be constructed using the syntax <code>T[A, B, C, ...]</code>. This will construct a 1-d array with element type <code>T</code>, initialized to contain elements <code>A</code>, <code>B</code>, <code>C</code>, etc. For example <code>Any[x, y, z]</code> constructs a heterogeneous array that can contain any values.</p><p>Concatenation syntax can similarly be prefixed with a type to specify the element type of the result.</p><pre><code class="language-julia-repl">julia> [[1 2] [3 4]]
|
||
1×4 Array{Int64,2}:
|
||
1 2 3 4
|
||
|
||
julia> Int8[[1 2] [3 4]]
|
||
1×4 Array{Int8,2}:
|
||
1 2 3 4</code></pre><h3><a class="nav-anchor" id="Comprehensions-1" href="#Comprehensions-1">Comprehensions</a></h3><p>Comprehensions provide a general and powerful way to construct arrays. Comprehension syntax is similar to set construction notation in mathematics:</p><pre><code class="language-none">A = [ F(x,y,...) for x=rx, y=ry, ... ]</code></pre><p>The meaning of this form is that <code>F(x,y,...)</code> is evaluated with the variables <code>x</code>, <code>y</code>, etc. taking on each value in their given list of values. Values can be specified as any iterable object, but will commonly be ranges like <code>1:n</code> or <code>2:(n-1)</code>, or explicit arrays of values like <code>[1.2, 3.4, 5.7]</code>. The result is an N-d dense array with dimensions that are the concatenation of the dimensions of the variable ranges <code>rx</code>, <code>ry</code>, etc. and each <code>F(x,y,...)</code> evaluation returns a scalar.</p><p>The following example computes a weighted average of the current element and its left and right neighbor along a 1-d grid. :</p><pre><code class="language-julia-repl">julia> x = rand(8)
|
||
8-element Array{Float64,1}:
|
||
0.843025
|
||
0.869052
|
||
0.365105
|
||
0.699456
|
||
0.977653
|
||
0.994953
|
||
0.41084
|
||
0.809411
|
||
|
||
julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
|
||
6-element Array{Float64,1}:
|
||
0.736559
|
||
0.57468
|
||
0.685417
|
||
0.912429
|
||
0.8446
|
||
0.656511</code></pre><p>The resulting array type depends on the types of the computed elements. In order to control the type explicitly, a type can be prepended to the comprehension. For example, we could have requested the result in single precision by writing:</p><pre><code class="language-julia">Float32[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]</code></pre><h3><a class="nav-anchor" id="Generator-Expressions-1" href="#Generator-Expressions-1">Generator Expressions</a></h3><p>Comprehensions can also be written without the enclosing square brackets, producing an object known as a generator. This object can be iterated to produce values on demand, instead of allocating an array and storing them in advance (see <a href="arrays.html#Iteration-1">Iteration</a>). For example, the following expression sums a series without allocating memory:</p><pre><code class="language-julia-repl">julia> sum(1/n^2 for n=1:1000)
|
||
1.6439345666815615</code></pre><p>When writing a generator expression with multiple dimensions inside an argument list, parentheses are needed to separate the generator from subsequent arguments:</p><pre><code class="language-julia-repl">julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])
|
||
ERROR: syntax: invalid iteration specification</code></pre><p>All comma-separated expressions after <code>for</code> are interpreted as ranges. Adding parentheses lets us add a third argument to <code>map</code>:</p><pre><code class="language-julia-repl">julia> map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4])
|
||
2×2 Array{Tuple{Float64,Int64},2}:
|
||
(0.5, 1) (0.333333, 3)
|
||
(0.333333, 2) (0.25, 4)</code></pre><p>Ranges in generators and comprehensions can depend on previous ranges by writing multiple <code>for</code> keywords:</p><pre><code class="language-julia-repl">julia> [(i,j) for i=1:3 for j=1:i]
|
||
6-element Array{Tuple{Int64,Int64},1}:
|
||
(1, 1)
|
||
(2, 1)
|
||
(2, 2)
|
||
(3, 1)
|
||
(3, 2)
|
||
(3, 3)</code></pre><p>In such cases, the result is always 1-d.</p><p>Generated values can be filtered using the <code>if</code> keyword:</p><pre><code class="language-julia-repl">julia> [(i,j) for i=1:3 for j=1:i if i+j == 4]
|
||
2-element Array{Tuple{Int64,Int64},1}:
|
||
(2, 2)
|
||
(3, 1)</code></pre><h3><a class="nav-anchor" id="man-array-indexing-1" href="#man-array-indexing-1">Indexing</a></h3><p>The general syntax for indexing into an n-dimensional array A is:</p><pre><code class="language-none">X = A[I_1, I_2, ..., I_n]</code></pre><p>where each <code>I_k</code> may be a scalar integer, an array of integers, or any other <a href="arrays.html#man-supported-index-types-1">supported index</a>. This includes <a href="../stdlib/arrays.html#Base.Colon"><code>Colon</code></a> (<code>:</code>) to select all indices within the entire dimension, ranges of the form <code>a:c</code> or <code>a:b:c</code> to select contiguous or strided subsections, and arrays of booleans to select elements at their <code>true</code> indices.</p><p>If all the indices are scalars, then the result <code>X</code> is a single element from the array <code>A</code>. Otherwise, <code>X</code> is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.</p><p>If all indices are vectors, for example, then the shape of <code>X</code> would be <code>(length(I_1), length(I_2), ..., length(I_n))</code>, with location <code>(i_1, i_2, ..., i_n)</code> of <code>X</code> containing the value <code>A[I_1[i_1], I_2[i_2], ..., I_n[i_n]]</code>. If <code>I_1</code> is changed to a two-dimensional matrix, then <code>X</code> becomes an <code>n+1</code>-dimensional array of shape <code>(size(I_1, 1), size(I_1, 2), length(I_2), ..., length(I_n))</code>. The matrix adds a dimension. The location <code>(i_1, i_2, i_3, ..., i_{n+1})</code> contains the value at <code>A[I_1[i_1, i_2], I_2[i_3], ..., I_n[i_{n+1}]]</code>. All dimensions indexed with scalars are dropped. For example, the result of <code>A[2, I, 3]</code> is an array with size <code>size(I)</code>. Its <code>i</code>th element is populated by <code>A[2, I[i], 3]</code>.</p><p>As a special part of this syntax, the <code>end</code> keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the innermost array being indexed. Indexing syntax without the <code>end</code> keyword is equivalent to a call to <code>getindex</code>:</p><pre><code class="language-none">X = getindex(A, I_1, I_2, ..., I_n)</code></pre><p>Example:</p><pre><code class="language-julia-repl">julia> x = reshape(1:16, 4, 4)
|
||
4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
|
||
1 5 9 13
|
||
2 6 10 14
|
||
3 7 11 15
|
||
4 8 12 16
|
||
|
||
julia> x[2:3, 2:end-1]
|
||
2×2 Array{Int64,2}:
|
||
6 10
|
||
7 11
|
||
|
||
julia> x[1, [2 3; 4 1]]
|
||
2×2 Array{Int64,2}:
|
||
5 9
|
||
13 1</code></pre><p>Empty ranges of the form <code>n:n-1</code> are sometimes used to indicate the inter-index location between <code>n-1</code> and <code>n</code>. For example, the <a href="../stdlib/sort.html#Base.Sort.searchsorted"><code>searchsorted()</code></a> function uses this convention to indicate the insertion point of a value not found in a sorted array:</p><pre><code class="language-julia-repl">julia> a = [1,2,5,6,7];
|
||
|
||
julia> searchsorted(a, 3)
|
||
3:2</code></pre><h3><a class="nav-anchor" id="Assignment-1" href="#Assignment-1">Assignment</a></h3><p>The general syntax for assigning values in an n-dimensional array A is:</p><pre><code class="language-none">A[I_1, I_2, ..., I_n] = X</code></pre><p>where each <code>I_k</code> may be a scalar integer, an array of integers, or any other <a href="arrays.html#man-supported-index-types-1">supported index</a>. This includes <a href="../stdlib/arrays.html#Base.Colon"><code>Colon</code></a> (<code>:</code>) to select all indices within the entire dimension, ranges of the form <code>a:c</code> or <code>a:b:c</code> to select contiguous or strided subsections, and arrays of booleans to select elements at their <code>true</code> indices.</p><p>If <code>X</code> is an array, it must have the same number of elements as the product of the lengths of the indices: <code>prod(length(I_1), length(I_2), ..., length(I_n))</code>. The value in location <code>I_1[i_1], I_2[i_2], ..., I_n[i_n]</code> of <code>A</code> is overwritten with the value <code>X[i_1, i_2, ..., i_n]</code>. If <code>X</code> is not an array, its value is written to all referenced locations of <code>A</code>.</p><p>Just as in <a href="arrays.html#man-array-indexing-1">Indexing</a>, the <code>end</code> keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the array being assigned into. Indexed assignment syntax without the <code>end</code> keyword is equivalent to a call to <a href="../stdlib/arrays.html#Base.setindex!-Tuple{AbstractArray,Any,Vararg{Any,N} where N}"><code>setindex!()</code></a>:</p><pre><code class="language-none">setindex!(A, X, I_1, I_2, ..., I_n)</code></pre><p>Example:</p><pre><code class="language-julia-repl">julia> x = collect(reshape(1:9, 3, 3))
|
||
3×3 Array{Int64,2}:
|
||
1 4 7
|
||
2 5 8
|
||
3 6 9
|
||
|
||
julia> x[1:2, 2:3] = -1
|
||
-1
|
||
|
||
julia> x
|
||
3×3 Array{Int64,2}:
|
||
1 -1 -1
|
||
2 -1 -1
|
||
3 6 9</code></pre><h3><a class="nav-anchor" id="man-supported-index-types-1" href="#man-supported-index-types-1">Supported index types</a></h3><p>In the expression <code>A[I_1, I_2, ..., I_n]</code>, each <code>I_k</code> may be a scalar index, an array of scalar indices, or an object that represents an array of scalar indices and can be converted to such by <a href="../stdlib/arrays.html#Base.to_indices"><code>to_indices</code></a>:</p><ol><li><p>A scalar index. By default this includes:</p><ul><li><p>Non-boolean integers</p></li><li><p><code>CartesianIndex{N}</code>s, which behave like an <code>N</code>-tuple of integers spanning multiple dimensions (see below for more details)</p></li></ul></li><li><p>An array of scalar indices. This includes:</p><ul><li><p>Vectors and multidimensional arrays of integers</p></li><li><p>Empty arrays like <code>[]</code>, which select no elements</p></li><li><p><code>Range</code>s of the form <code>a:c</code> or <code>a:b:c</code>, which select contiguous or strided subsections from <code>a</code> to <code>c</code> (inclusive)</p></li><li><p>Any custom array of scalar indices that is a subtype of <code>AbstractArray</code></p></li><li><p>Arrays of <code>CartesianIndex{N}</code> (see below for more details)</p></li></ul></li><li><p>An object that represents an array of scalar indices and can be converted to such by <a href="../stdlib/arrays.html#Base.to_indices"><code>to_indices</code></a>. By default this includes:</p><ul><li><p><a href="../stdlib/arrays.html#Base.Colon"><code>Colon()</code></a> (<code>:</code>), which represents all indices within an entire dimension or across the entire array</p></li><li><p>Arrays of booleans, which select elements at their <code>true</code> indices (see below for more details)</p></li></ul></li></ol><h4><a class="nav-anchor" id="Cartesian-indices-1" href="#Cartesian-indices-1">Cartesian indices</a></h4><p>The special <code>CartesianIndex{N}</code> object represents a scalar index that behaves like an <code>N</code>-tuple of integers spanning multiple dimensions. For example:</p><pre><code class="language-jldoctest">julia> A = reshape(1:32, 4, 4, 2);
|
||
|
||
julia> A[3, 2, 1]
|
||
7
|
||
|
||
julia> A[CartesianIndex(3, 2, 1)] == A[3, 2, 1] == 7
|
||
true</code></pre><p>Considered alone, this may seem relatively trivial; <code>CartesianIndex</code> simply gathers multiple integers together into one object that represents a single multidimensional index. When combined with other indexing forms and iterators that yield <code>CartesianIndex</code>es, however, this can lead directly to very elegant and efficient code. See <a href="arrays.html#Iteration-1">Iteration</a> below, and for some more advanced examples, see <a href="https://julialang.org/blog/2016/02/iteration">this blog post on multidimensional algorithms and iteration</a>.</p><p>Arrays of <code>CartesianIndex{N}</code> are also supported. They represent a collection of scalar indices that each span <code>N</code> dimensions, enabling a form of indexing that is sometimes referred to as pointwise indexing. For example, it enables accessing the diagonal elements from the first "page" of <code>A</code> from above:</p><pre><code class="language-jldoctest">julia> page = A[:,:,1]
|
||
4×4 Array{Int64,2}:
|
||
1 5 9 13
|
||
2 6 10 14
|
||
3 7 11 15
|
||
4 8 12 16
|
||
|
||
julia> page[[CartesianIndex(1,1),
|
||
CartesianIndex(2,2),
|
||
CartesianIndex(3,3),
|
||
CartesianIndex(4,4)]]
|
||
4-element Array{Int64,1}:
|
||
1
|
||
6
|
||
11
|
||
16</code></pre><p>This can be expressed much more simply with <a href="functions.html#man-vectorized-1">dot broadcasting</a> and by combining it with a normal integer index (instead of extracting the first <code>page</code> from <code>A</code> as a separate step). It can even be combined with a <code>:</code> to extract both diagonals from the two pages at the same time:</p><pre><code class="language-jldoctest">julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), 1]
|
||
4-element Array{Int64,1}:
|
||
1
|
||
6
|
||
11
|
||
16
|
||
|
||
julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), :]
|
||
4×2 Array{Int64,2}:
|
||
1 17
|
||
6 22
|
||
11 27
|
||
16 32</code></pre><div class="admonition warning"><div class="admonition-title">Warning</div><div class="admonition-text"><p><code>CartesianIndex</code> and arrays of <code>CartesianIndex</code> are not compatible with the <code>end</code> keyword to represent the last index of a dimension. Do not use <code>end</code> in indexing expressions that may contain either <code>CartesianIndex</code> or arrays thereof.</p></div></div><h4><a class="nav-anchor" id="Logical-indexing-1" href="#Logical-indexing-1">Logical indexing</a></h4><p>Often referred to as logical indexing or indexing with a logical mask, indexing by a boolean array selects elements at the indices where its values are <code>true</code>. Indexing by a boolean vector <code>B</code> is effectively the same as indexing by the vector of integers that is returned by <a href="../stdlib/arrays.html#Base.find-Tuple{Any}"><code>find(B)</code></a>. Similarly, indexing by a <code>N</code>-dimensional boolean array is effectively the same as indexing by the vector of <code>CartesianIndex{N}</code>s where its values are <code>true</code>. A logical index must be a vector of the same length as the dimension it indexes into, or it must be the only index provided and match the size and dimensionality of the array it indexes into. It is generally more efficient to use boolean arrays as indices directly instead of first calling <a href="../stdlib/arrays.html#Base.find-Tuple{Any}"><code>find()</code></a>.</p><pre><code class="language-julia-repl">julia> x = reshape(1:16, 4, 4)
|
||
4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
|
||
1 5 9 13
|
||
2 6 10 14
|
||
3 7 11 15
|
||
4 8 12 16
|
||
|
||
julia> x[[false, true, true, false], :]
|
||
2×4 Array{Int64,2}:
|
||
2 6 10 14
|
||
3 7 11 15
|
||
|
||
julia> mask = map(ispow2, x)
|
||
4×4 Array{Bool,2}:
|
||
true false false false
|
||
true false false false
|
||
false false false false
|
||
true true false true
|
||
|
||
julia> x[mask]
|
||
5-element Array{Int64,1}:
|
||
1
|
||
2
|
||
4
|
||
8
|
||
16</code></pre><h3><a class="nav-anchor" id="Iteration-1" href="#Iteration-1">Iteration</a></h3><p>The recommended ways to iterate over a whole array are</p><pre><code class="language-julia">for a in A
|
||
# Do something with the element a
|
||
end
|
||
|
||
for i in eachindex(A)
|
||
# Do something with i and/or A[i]
|
||
end</code></pre><p>The first construct is used when you need the value, but not index, of each element. In the second construct, <code>i</code> will be an <code>Int</code> if <code>A</code> is an array type with fast linear indexing; otherwise, it will be a <code>CartesianIndex</code>:</p><pre><code class="language-julia-repl">julia> A = rand(4,3);
|
||
|
||
julia> B = view(A, 1:3, 2:3);
|
||
|
||
julia> for i in eachindex(B)
|
||
@show i
|
||
end
|
||
i = CartesianIndex{2}((1, 1))
|
||
i = CartesianIndex{2}((2, 1))
|
||
i = CartesianIndex{2}((3, 1))
|
||
i = CartesianIndex{2}((1, 2))
|
||
i = CartesianIndex{2}((2, 2))
|
||
i = CartesianIndex{2}((3, 2))</code></pre><p>In contrast with <code>for i = 1:length(A)</code>, iterating with <code>eachindex</code> provides an efficient way to iterate over any array type.</p><h3><a class="nav-anchor" id="Array-traits-1" href="#Array-traits-1">Array traits</a></h3><p>If you write a custom <a href="../stdlib/arrays.html#Core.AbstractArray"><code>AbstractArray</code></a> type, you can specify that it has fast linear indexing using</p><pre><code class="language-julia">Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()</code></pre><p>This setting will cause <code>eachindex</code> iteration over a <code>MyArray</code> to use integers. If you don't specify this trait, the default value <code>IndexCartesian()</code> is used.</p><h3><a class="nav-anchor" id="Array-and-Vectorized-Operators-and-Functions-1" href="#Array-and-Vectorized-Operators-and-Functions-1">Array and Vectorized Operators and Functions</a></h3><p>The following operators are supported for arrays:</p><ol><li><p>Unary arithmetic – <code>-</code>, <code>+</code></p></li><li><p>Binary arithmetic – <code>-</code>, <code>+</code>, <code>*</code>, <code>/</code>, <code>\</code>, <code>^</code></p></li><li><p>Comparison – <code>==</code>, <code>!=</code>, <code>≈</code> (<a href="../stdlib/math.html#Base.isapprox"><code>isapprox</code></a>), <code>≉</code></p></li></ol><p>Most of the binary arithmetic operators listed above also operate elementwise when one argument is scalar: <code>-</code>, <code>+</code>, and <code>*</code> when either argument is scalar, and <code>/</code> and <code>\</code> when the denominator is scalar. For example, <code>[1, 2] + 3 == [4, 5]</code> and <code>[6, 4] / 2 == [3, 2]</code>.</p><p>Additionally, to enable convenient vectorization of mathematical and other operations, Julia <a href="functions.html#man-vectorized-1">provides the dot syntax</a> <code>f.(args...)</code>, e.g. <code>sin.(x)</code> or <code>min.(x,y)</code>, for elementwise operations over arrays or mixtures of arrays and scalars (a <a href="arrays.html#Broadcasting-1">Broadcasting</a> operation); these have the additional advantage of "fusing" into a single loop when combined with other dot calls, e.g. <code>sin.(cos.(x))</code>.</p><p>Also, <em>every</em> binary operator supports a <a href="mathematical-operations.html#man-dot-operators-1">dot version</a> that can be applied to arrays (and combinations of arrays and scalars) in such <a href="functions.html#man-vectorized-1">fused broadcasting operations</a>, e.g. <code>z .== sin.(x .* y)</code>.</p><p>Note that comparisons such as <code>==</code> operate on whole arrays, giving a single boolean answer. Use dot operators like <code>.==</code> for elementwise comparisons. (For comparison operations like <code><</code>, <em>only</em> the elementwise <code>.<</code> version is applicable to arrays.)</p><p>Also notice the difference between <code>max.(a,b)</code>, which <code>broadcast</code>s <a href="../stdlib/math.html#Base.max"><code>max()</code></a> elementwise over <code>a</code> and <code>b</code>, and <code>maximum(a)</code>, which finds the largest value within <code>a</code>. The same relationship holds for <code>min.(a,b)</code> and <code>minimum(a)</code>.</p><h3><a class="nav-anchor" id="Broadcasting-1" href="#Broadcasting-1">Broadcasting</a></h3><p>It is sometimes useful to perform element-by-element binary operations on arrays of different sizes, such as adding a vector to each column of a matrix. An inefficient way to do this would be to replicate the vector to the size of the matrix:</p><pre><code class="language-julia-repl">julia> a = rand(2,1); A = rand(2,3);
|
||
|
||
julia> repmat(a,1,3)+A
|
||
2×3 Array{Float64,2}:
|
||
1.20813 1.82068 1.25387
|
||
1.56851 1.86401 1.67846</code></pre><p>This is wasteful when dimensions get large, so Julia offers <a href="../stdlib/arrays.html#Base.broadcast"><code>broadcast()</code></a>, which expands singleton dimensions in array arguments to match the corresponding dimension in the other array without using extra memory, and applies the given function elementwise:</p><pre><code class="language-julia-repl">julia> broadcast(+, a, A)
|
||
2×3 Array{Float64,2}:
|
||
1.20813 1.82068 1.25387
|
||
1.56851 1.86401 1.67846
|
||
|
||
julia> b = rand(1,2)
|
||
1×2 Array{Float64,2}:
|
||
0.867535 0.00457906
|
||
|
||
julia> broadcast(+, a, b)
|
||
2×2 Array{Float64,2}:
|
||
1.71056 0.847604
|
||
1.73659 0.873631</code></pre><p><a href="mathematical-operations.html#man-dot-operators-1">Dotted operators</a> such as <code>.+</code> and <code>.*</code> are equivalent to <code>broadcast</code> calls (except that they fuse, as described below). There is also a <a href="../stdlib/arrays.html#Base.broadcast!"><code>broadcast!()</code></a> function to specify an explicit destination (which can also be accessed in a fusing fashion by <code>.=</code> assignment), and functions <a href="../stdlib/arrays.html#Base.Broadcast.broadcast_getindex"><code>broadcast_getindex()</code></a> and <a href="../stdlib/arrays.html#Base.Broadcast.broadcast_setindex!"><code>broadcast_setindex!()</code></a> that broadcast the indices before indexing. Moreover, <code>f.(args...)</code> is equivalent to <code>broadcast(f, args...)</code>, providing a convenient syntax to broadcast any function (<a href="functions.html#man-vectorized-1">dot syntax</a>). Nested "dot calls" <code>f.(...)</code> (including calls to <code>.+</code> etcetera) <a href="mathematical-operations.html#man-dot-operators-1">automatically fuse</a> into a single <code>broadcast</code> call.</p><p>Additionally, <a href="../stdlib/arrays.html#Base.broadcast"><code>broadcast()</code></a> is not limited to arrays (see the function documentation), it also handles tuples and treats any argument that is not an array, tuple or <code>Ref</code> (except for <code>Ptr</code>) as a "scalar".</p><pre><code class="language-julia-repl">julia> convert.(Float32, [1, 2])
|
||
2-element Array{Float32,1}:
|
||
1.0
|
||
2.0
|
||
|
||
julia> ceil.((UInt8,), [1.2 3.4; 5.6 6.7])
|
||
2×2 Array{UInt8,2}:
|
||
0x02 0x04
|
||
0x06 0x07
|
||
|
||
julia> string.(1:3, ". ", ["First", "Second", "Third"])
|
||
3-element Array{String,1}:
|
||
"1. First"
|
||
"2. Second"
|
||
"3. Third"</code></pre><h3><a class="nav-anchor" id="Implementation-1" href="#Implementation-1">Implementation</a></h3><p>The base array type in Julia is the abstract type <code>AbstractArray{T,N}</code>. It is parametrized by the number of dimensions <code>N</code> and the element type <code>T</code>. <code>AbstractVector</code> and <code>AbstractMatrix</code> are aliases for the 1-d and 2-d cases. Operations on <code>AbstractArray</code> objects are defined using higher level operators and functions, in a way that is independent of the underlying storage. These operations generally work correctly as a fallback for any specific array implementation.</p><p>The <code>AbstractArray</code> type includes anything vaguely array-like, and implementations of it might be quite different from conventional arrays. For example, elements might be computed on request rather than stored. However, any concrete <code>AbstractArray{T,N}</code> type should generally implement at least <a href="../stdlib/arrays.html#Base.size"><code>size(A)</code></a> (returning an <code>Int</code> tuple), <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex(A,i)</code></a> and <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex(A,i1,...,iN)</code></a>; mutable arrays should also implement <a href="../stdlib/arrays.html#Base.setindex!-Tuple{AbstractArray,Any,Vararg{Any,N} where N}"><code>setindex!()</code></a>. It is recommended that these operations have nearly constant time complexity, or technically Õ(1) complexity, as otherwise some array functions may be unexpectedly slow. Concrete types should also typically provide a <a href="../stdlib/arrays.html#Base.similar-Tuple{AbstractArray}"><code>similar(A,T=eltype(A),dims=size(A))</code></a> method, which is used to allocate a similar array for <a href="../stdlib/base.html#Base.copy"><code>copy()</code></a> and other out-of-place operations. No matter how an <code>AbstractArray{T,N}</code> is represented internally, <code>T</code> is the type of object returned by <em>integer</em> indexing (<code>A[1, ..., 1]</code>, when <code>A</code> is not empty) and <code>N</code> should be the length of the tuple returned by <a href="../stdlib/arrays.html#Base.size"><code>size()</code></a>.</p><p><code>DenseArray</code> is an abstract subtype of <code>AbstractArray</code> intended to include all arrays that are laid out at regular offsets in memory, and which can therefore be passed to external C and Fortran functions expecting this memory layout. Subtypes should provide a method <a href="../stdlib/arrays.html#Base.stride"><code>stride(A,k)</code></a> that returns the "stride" of dimension <code>k</code>: increasing the index of dimension <code>k</code> by <code>1</code> should increase the index <code>i</code> of <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex(A,i)</code></a> by <a href="../stdlib/arrays.html#Base.stride"><code>stride(A,k)</code></a>. If a pointer conversion method <a href="../stdlib/c.html#Base.unsafe_convert"><code>Base.unsafe_convert(Ptr{T}, A)</code></a> is provided, the memory layout should correspond in the same way to these strides.</p><p>The <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a> type is a specific instance of <code>DenseArray</code> where elements are stored in column-major order (see additional notes in <a href="performance-tips.html#man-performance-tips-1">Performance Tips</a>). <code>Vector</code> and <code>Matrix</code> are aliases for the 1-d and 2-d cases. Specific operations such as scalar indexing, assignment, and a few other basic storage-specific operations are all that have to be implemented for <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a>, so that the rest of the array library can be implemented in a generic manner.</p><p><code>SubArray</code> is a specialization of <code>AbstractArray</code> that performs indexing by reference rather than by copying. A <code>SubArray</code> is created with the <a href="../stdlib/arrays.html#Base.view"><code>view()</code></a> function, which is called the same way as <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex()</code></a> (with an array and a series of index arguments). The result of <a href="../stdlib/arrays.html#Base.view"><code>view()</code></a> looks the same as the result of <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex()</code></a>, except the data is left in place. <a href="../stdlib/arrays.html#Base.view"><code>view()</code></a> stores the input index vectors in a <code>SubArray</code> object, which can later be used to index the original array indirectly. By putting the <a href="../stdlib/arrays.html#Base.@views"><code>@views</code></a> macro in front of an expression or block of code, any <code>array[...]</code> slice in that expression will be converted to create a <code>SubArray</code> view instead.</p><p><code>StridedVector</code> and <code>StridedMatrix</code> are convenient aliases defined to make it possible for Julia to call a wider range of BLAS and LAPACK functions by passing them either <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a> or <code>SubArray</code> objects, and thus saving inefficiencies from memory allocation and copying.</p><p>The following example computes the QR decomposition of a small section of a larger array, without creating any temporaries, and by calling the appropriate LAPACK function with the right leading dimension size and stride parameters.</p><pre><code class="language-julia-repl">julia> a = rand(10,10)
|
||
10×10 Array{Float64,2}:
|
||
0.561255 0.226678 0.203391 0.308912 … 0.750307 0.235023 0.217964
|
||
0.718915 0.537192 0.556946 0.996234 0.666232 0.509423 0.660788
|
||
0.493501 0.0565622 0.118392 0.493498 0.262048 0.940693 0.252965
|
||
0.0470779 0.736979 0.264822 0.228787 0.161441 0.897023 0.567641
|
||
0.343935 0.32327 0.795673 0.452242 0.468819 0.628507 0.511528
|
||
0.935597 0.991511 0.571297 0.74485 … 0.84589 0.178834 0.284413
|
||
0.160706 0.672252 0.133158 0.65554 0.371826 0.770628 0.0531208
|
||
0.306617 0.836126 0.301198 0.0224702 0.39344 0.0370205 0.536062
|
||
0.890947 0.168877 0.32002 0.486136 0.096078 0.172048 0.77672
|
||
0.507762 0.573567 0.220124 0.165816 0.211049 0.433277 0.539476
|
||
|
||
julia> b = view(a, 2:2:8,2:2:4)
|
||
4×2 SubArray{Float64,2,Array{Float64,2},Tuple{StepRange{Int64,Int64},StepRange{Int64,Int64}},false}:
|
||
0.537192 0.996234
|
||
0.736979 0.228787
|
||
0.991511 0.74485
|
||
0.836126 0.0224702
|
||
|
||
julia> (q,r) = qr(b);
|
||
|
||
julia> q
|
||
4×2 Array{Float64,2}:
|
||
-0.338809 0.78934
|
||
-0.464815 -0.230274
|
||
-0.625349 0.194538
|
||
-0.527347 -0.534856
|
||
|
||
julia> r
|
||
2×2 Array{Float64,2}:
|
||
-1.58553 -0.921517
|
||
0.0 0.866567</code></pre><h2><a class="nav-anchor" id="Sparse-Vectors-and-Matrices-1" href="#Sparse-Vectors-and-Matrices-1">Sparse Vectors and Matrices</a></h2><p>Julia has built-in support for sparse vectors and <a href="https://en.wikipedia.org/wiki/Sparse_matrix">sparse matrices</a>. Sparse arrays are arrays that contain enough zeros that storing them in a special data structure leads to savings in space and execution time, compared to dense arrays.</p><h3><a class="nav-anchor" id="man-csc-1" href="#man-csc-1">Compressed Sparse Column (CSC) Sparse Matrix Storage</a></h3><p>In Julia, sparse matrices are stored in the <a href="https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_.28CSC_or_CCS.29">Compressed Sparse Column (CSC) format</a>. Julia sparse matrices have the type <a href="../stdlib/arrays.html#Base.SparseArrays.SparseMatrixCSC"><code>SparseMatrixCSC{Tv,Ti}</code></a>, where <code>Tv</code> is the type of the stored values, and <code>Ti</code> is the integer type for storing column pointers and row indices. The internal representation of <code>SparseMatrixCSC</code> is as follows:</p><pre><code class="language-julia">struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}
|
||
m::Int # Number of rows
|
||
n::Int # Number of columns
|
||
colptr::Vector{Ti} # Column i is in colptr[i]:(colptr[i+1]-1)
|
||
rowval::Vector{Ti} # Row indices of stored values
|
||
nzval::Vector{Tv} # Stored values, typically nonzeros
|
||
end</code></pre><p>The compressed sparse column storage makes it easy and quick to access the elements in the column of a sparse matrix, whereas accessing the sparse matrix by rows is considerably slower. Operations such as insertion of previously unstored entries one at a time in the CSC structure tend to be slow. This is because all elements of the sparse matrix that are beyond the point of insertion have to be moved one place over.</p><p>All operations on sparse matrices are carefully implemented to exploit the CSC data structure for performance, and to avoid expensive operations.</p><p>If you have data in CSC format from a different application or library, and wish to import it in Julia, make sure that you use 1-based indexing. The row indices in every column need to be sorted. If your <code>SparseMatrixCSC</code> object contains unsorted row indices, one quick way to sort them is by doing a double transpose.</p><p>In some applications, it is convenient to store explicit zero values in a <code>SparseMatrixCSC</code>. These <em>are</em> accepted by functions in <code>Base</code> (but there is no guarantee that they will be preserved in mutating operations). Such explicitly stored zeros are treated as structural nonzeros by many routines. The <a href="../stdlib/arrays.html#Base.SparseArrays.nnz"><code>nnz()</code></a> function returns the number of elements explicitly stored in the sparse data structure, including structural nonzeros. In order to count the exact number of numerical nonzeros, use <a href="../stdlib/arrays.html#Base.countnz"><code>countnz()</code></a>, which inspects every stored element of a sparse matrix. <a href="../stdlib/arrays.html#Base.SparseArrays.dropzeros-Tuple{SparseMatrixCSC,Bool}"><code>dropzeros()</code></a>, and the in-place <a href="../stdlib/arrays.html#Base.SparseArrays.dropzeros!-Tuple{SparseMatrixCSC,Bool}"><code>dropzeros!()</code></a>, can be used to remove stored zeros from the sparse matrix.</p><pre><code class="language-julia-repl">julia> A = sparse([1, 2, 3], [1, 2, 3], [0, 2, 0])
|
||
3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
|
||
[1, 1] = 0
|
||
[2, 2] = 2
|
||
[3, 3] = 0
|
||
|
||
julia> dropzeros(A)
|
||
3×3 SparseMatrixCSC{Int64,Int64} with 1 stored entry:
|
||
[2, 2] = 2</code></pre><h3><a class="nav-anchor" id="Sparse-Vector-Storage-1" href="#Sparse-Vector-Storage-1">Sparse Vector Storage</a></h3><p>Sparse vectors are stored in a close analog to compressed sparse column format for sparse matrices. In Julia, sparse vectors have the type <a href="../stdlib/arrays.html#Base.SparseArrays.SparseVector"><code>SparseVector{Tv,Ti}</code></a> where <code>Tv</code> is the type of the stored values and <code>Ti</code> the integer type for the indices. The internal representation is as follows:</p><pre><code class="language-julia">struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
|
||
n::Int # Length of the sparse vector
|
||
nzind::Vector{Ti} # Indices of stored values
|
||
nzval::Vector{Tv} # Stored values, typically nonzeros
|
||
end</code></pre><p>As for <a href="../stdlib/arrays.html#Base.SparseArrays.SparseMatrixCSC"><code>SparseMatrixCSC</code></a>, the <code>SparseVector</code> type can also contain explicitly stored zeros. (See <a href="arrays.html#man-csc-1">Sparse Matrix Storage</a>.).</p><h3><a class="nav-anchor" id="Sparse-Vector-and-Matrix-Constructors-1" href="#Sparse-Vector-and-Matrix-Constructors-1">Sparse Vector and Matrix Constructors</a></h3><p>The simplest way to create sparse arrays is to use functions equivalent to the <a href="../stdlib/arrays.html#Base.zeros"><code>zeros()</code></a> and <a href="../stdlib/arrays.html#Base.eye"><code>eye()</code></a> functions that Julia provides for working with dense arrays. To produce sparse arrays instead, you can use the same names with an <code>sp</code> prefix:</p><pre><code class="language-julia-repl">julia> spzeros(3)
|
||
3-element SparseVector{Float64,Int64} with 0 stored entries
|
||
|
||
julia> speye(3,5)
|
||
3×5 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
|
||
[1, 1] = 1.0
|
||
[2, 2] = 1.0
|
||
[3, 3] = 1.0</code></pre><p>The <a href="../stdlib/arrays.html#Base.SparseArrays.sparse"><code>sparse()</code></a> function is often a handy way to construct sparse arrays. For example, to construct a sparse matrix we can input a vector <code>I</code> of row indices, a vector <code>J</code> of column indices, and a vector <code>V</code> of stored values (this is also known as the <a href="https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_.28COO.29">COO (coordinate) format</a>). <code>sparse(I,J,V)</code> then constructs a sparse matrix such that <code>S[I[k], J[k]] = V[k]</code>. The equivalent sparse vector constructor is <a href="../stdlib/arrays.html#Base.SparseArrays.sparsevec"><code>sparsevec</code></a>, which takes the (row) index vector <code>I</code> and the vector <code>V</code> with the stored values and constructs a sparse vector <code>R</code> such that <code>R[I[k]] = V[k]</code>.</p><pre><code class="language-jldoctest">julia> I = [1, 4, 3, 5]; J = [4, 7, 18, 9]; V = [1, 2, -5, 3];
|
||
|
||
julia> S = sparse(I,J,V)
|
||
5×18 SparseMatrixCSC{Int64,Int64} with 4 stored entries:
|
||
[1 , 4] = 1
|
||
[4 , 7] = 2
|
||
[5 , 9] = 3
|
||
[3 , 18] = -5
|
||
|
||
julia> R = sparsevec(I,V)
|
||
5-element SparseVector{Int64,Int64} with 4 stored entries:
|
||
[1] = 1
|
||
[3] = -5
|
||
[4] = 2
|
||
[5] = 3</code></pre><p>The inverse of the <a href="../stdlib/arrays.html#Base.SparseArrays.sparse"><code>sparse()</code></a> and <a href="../stdlib/arrays.html#Base.SparseArrays.sparsevec"><code>sparsevec</code></a> functions is <a href="../stdlib/arrays.html#Base.findnz"><code>findnz()</code></a>, which retrieves the inputs used to create the sparse array. There is also a <a href="../stdlib/arrays.html#Base.findn"><code>findn</code></a> function which only returns the index vectors.</p><pre><code class="language-jldoctest">julia> findnz(S)
|
||
([1, 4, 5, 3], [4, 7, 9, 18], [1, 2, 3, -5])
|
||
|
||
julia> findn(S)
|
||
([1, 4, 5, 3], [4, 7, 9, 18])
|
||
|
||
julia> findnz(R)
|
||
([1, 3, 4, 5], [1, -5, 2, 3])
|
||
|
||
julia> findn(R)
|
||
4-element Array{Int64,1}:
|
||
1
|
||
3
|
||
4
|
||
5</code></pre><p>Another way to create a sparse array is to convert a dense array into a sparse array using the <a href="../stdlib/arrays.html#Base.SparseArrays.sparse"><code>sparse()</code></a> function:</p><pre><code class="language-julia-repl">julia> sparse(eye(5))
|
||
5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries:
|
||
[1, 1] = 1.0
|
||
[2, 2] = 1.0
|
||
[3, 3] = 1.0
|
||
[4, 4] = 1.0
|
||
[5, 5] = 1.0
|
||
|
||
julia> sparse([1.0, 0.0, 1.0])
|
||
3-element SparseVector{Float64,Int64} with 2 stored entries:
|
||
[1] = 1.0
|
||
[3] = 1.0</code></pre><p>You can go in the other direction using the <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a> constructor. The <a href="../stdlib/arrays.html#Base.SparseArrays.issparse"><code>issparse()</code></a> function can be used to query if a matrix is sparse.</p><pre><code class="language-julia-repl">julia> issparse(speye(5))
|
||
true</code></pre><h3><a class="nav-anchor" id="Sparse-matrix-operations-1" href="#Sparse-matrix-operations-1">Sparse matrix operations</a></h3><p>Arithmetic operations on sparse matrices also work as they do on dense matrices. Indexing of, assignment into, and concatenation of sparse matrices work in the same way as dense matrices. Indexing operations, especially assignment, are expensive, when carried out one element at a time. In many cases it may be better to convert the sparse matrix into <code>(I,J,V)</code> format using <a href="../stdlib/arrays.html#Base.findnz"><code>findnz()</code></a>, manipulate the values or the structure in the dense vectors <code>(I,J,V)</code>, and then reconstruct the sparse matrix.</p><h3><a class="nav-anchor" id="Correspondence-of-dense-and-sparse-methods-1" href="#Correspondence-of-dense-and-sparse-methods-1">Correspondence of dense and sparse methods</a></h3><p>The following table gives a correspondence between built-in methods on sparse matrices and their corresponding methods on dense matrix types. In general, methods that generate sparse matrices differ from their dense counterparts in that the resulting matrix follows the same sparsity pattern as a given sparse matrix <code>S</code>, or that the resulting sparse matrix has density <code>d</code>, i.e. each matrix element has a probability <code>d</code> of being non-zero.</p><p>Details can be found in the <a href="../stdlib/arrays.html#stdlib-sparse-arrays-1">Sparse Vectors and Matrices</a> section of the standard library reference.</p><table><tr><th>Sparse</th><th>Dense</th><th>Description</th></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.spzeros"><code>spzeros(m,n)</code></a></td><td><a href="../stdlib/arrays.html#Base.zeros"><code>zeros(m,n)</code></a></td><td>Creates a <em>m</em>-by-<em>n</em> matrix of zeros. (<a href="../stdlib/arrays.html#Base.SparseArrays.spzeros"><code>spzeros(m,n)</code></a> is empty.)</td></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.spones"><code>spones(S)</code></a></td><td><a href="../stdlib/arrays.html#Base.ones"><code>ones(m,n)</code></a></td><td>Creates a matrix filled with ones. Unlike the dense version, <a href="../stdlib/arrays.html#Base.SparseArrays.spones"><code>spones()</code></a> has the same sparsity pattern as <em>S</em>.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.speye-Tuple{Type,Integer,Integer}"><code>speye(n)</code></a></td><td><a href="../stdlib/arrays.html#Base.eye"><code>eye(n)</code></a></td><td>Creates a <em>n</em>-by-<em>n</em> identity matrix.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.full"><code>full(S)</code></a></td><td><a href="../stdlib/arrays.html#Base.SparseArrays.sparse"><code>sparse(A)</code></a></td><td>Interconverts between dense and sparse formats.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.sprand"><code>sprand(m,n,d)</code></a></td><td><a href="../stdlib/numbers.html#Base.Random.rand"><code>rand(m,n)</code></a></td><td>Creates a <em>m</em>-by-<em>n</em> random matrix (of density <em>d</em>) with iid non-zero elements distributed uniformly on the half-open interval <span>$[0, 1)$</span>.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.sprandn"><code>sprandn(m,n,d)</code></a></td><td><a href="../stdlib/numbers.html#Base.Random.randn"><code>randn(m,n)</code></a></td><td>Creates a <em>m</em>-by-<em>n</em> random matrix (of density <em>d</em>) with iid non-zero elements distributed according to the standard normal (Gaussian) distribution.</td></tr><tr><td><a href="../stdlib/arrays.html#Base.SparseArrays.sprandn"><code>sprandn(m,n,d,X)</code></a></td><td><a href="../stdlib/numbers.html#Base.Random.randn"><code>randn(m,n,X)</code></a></td><td>Creates a <em>m</em>-by-<em>n</em> random matrix (of density <em>d</em>) with iid non-zero elements distributed according to the <em>X</em> distribution. (Requires the <code>Distributions</code> package.)</td></tr></table><footer><hr/><a class="previous" href="metaprogramming.html"><span class="direction">Previous</span><span class="title">Metaprogramming</span></a><a class="next" href="linear-algebra.html"><span class="direction">Next</span><span class="title">Linear algebra</span></a></footer></article></body></html>
|