# Introducing Julia/Arrays and tuples
## Storage: Arrays and Tuples

In Julia, groups of related items are usually stored in arrays, tuples, or dictionaries. Arrays can be used for storing vectors and matrices. This section concentrates on arrays and tuples; for more on dictionaries, see Dictionaries and Sets.

## Arrays

An array is an ordered collection of elements. It's often indicated with square brackets and comma-separated items. You can create arrays that are full or empty, and arrays that hold values of different types or restricted to values of a specific type.
In Julia, arrays are used for lists, vectors, tables, and matrices.
A one-dimensional array acts as a vector or list. A 2-D array can be used as a table or matrix. And 3-D and more-D arrays are similarly thought of as multi-dimensional matrices.

## Creating arrays
### Creating simple arrays

Here's how to create a simple one-dimensional array:
Julia informs you ("5-element Array{Int64,1}") that you've created a 1-dimensional array with 5 elements, each of which is a 64-bit integer, and bound the variable a to it. Notice that intelligence is applied to the process: if one of the elements looks like a floating-point number, for example, you'll get an array of Float64s:
Similarly for strings:
returns an array of strings, and:
returns an array of Julia functions.
There are many different ways to create arrays: you can make them empty, uninitialised, full, based on sequences, sparse, dense, and more besides. It depends on the task in hand.

#### Uninitialized

You can specify the type and the dimensions of an array using Array{type}(dims) (notice that upper-case "A"), putting the type in curly braces, and the dimensions in the parentheses. The undef means that the array hasn't been initialized to known values.
The random-looking numbers are a reminder that you've created an uninitialized array but haven't filled it with any sensible information.

#### Arrays of anything

It's possible to create arrays with elements of different types:
Here, the array has five elements, but they're an odd mixture: numbers, strings, functions, constants — so Julia creates an array of type Any:

#### Empty arrays

To create an array of a specific type, you can also use the type definition and square brackets:
If you think you can fool Julia by sneaking in a value of the wrong type while declaring a typed array, you'll be caught out:
You can create empty arrays this way too:

### Creating 2D arrays and matrices

If you leave out the commas when defining an array, you can create 2D arrays quickly. Here's a single row, multi-column array:
Notice the 1x4 {...,2} in the first row of the response.
You can use a semicolon to add another row:

#### Row and column vectors

Compare these two: [1,2,3,4,5] and [1 2 3 4 5].
With the commas, this array could be called a "column vector", with 5 rows and 1 column:
But with the spaces, this array could be called a "row vector", with 1 row and 5 columns:
- notice the {Int64,2} here, which tells you that this is a 2D array of Int64s (with 1 row and 5 columns). In both cases, they're standard Julia arrays.
Arrays created like this can be used as matrices:
And of course you can create arrays/matrices with 3 or more dimensions.
There are a number of functions which let you create and fill an array in one go. See Creating and filling an array.
Notice how Julia distinguishes between Array{Float64,1} and Array{Float64,2}:
Julia provides the Vector and Matrix constructor functions, but these are simply aliases for uninitialized one and two dimensional arrays:

### Creating arrays using range objects

In Julia, the colon (:) has a number of uses. One use is to define ranges and sequences of numbers. You can create a range object by typing it directly:
It may not look very useful in that form, but it provides the raw material for any job in Julia that needs a range or sequence of numbers.
You can use it in a loop expression:
Or you can use collect to build an array consisting of those numbers:
You don't have to start and finish on an integer either:
There's also a three-piece version of a range object, start:step:stop, which lets you specify a step size other than 1. For example, this builds an array with elements that go from 0 to 100 in steps of 10:
To go down instead of up, you have to use a negative step value:
Instead of using collect to create an array from the range, you could use the ellipsis (...) operator (three periods) after the last element:
(The ... ellipsis is sometimes called the splat operator. It represents a sequence of arguments.)
However, collect is faster and the recommended method of converting ranges to arrays. But you can use range objects in many situations in Julia, and you don't always need to expand them into arrays.

### More range objects

Another useful function is range, which constructs a range object that goes from a start value to an end value taking a specific number of steps of a certain size. You don't have to calculate all the information, because Julia calculates the missing pieces for you by combining the values for the keywords step, length, and stop. For example, to go from 1 to 100 in exactly 12 steps:
or take 10 steps from 1, stopping at or before 100:
If you really want it in array form, you can use the range object to build an array:
Notice that it provided you with a Float64 array, rather than an Integer array, even though the values could have been integers.
For logarithmic ranges (sometimes called 'log space'), you can use simple range objects and then broadcast the exp10 function (10^x) to every element of the range.
See Broadcasting and dot syntax.
Use step on a range object to find out what the step size is:
Use range if you know the start and step, but not the end, and you know how many elements you want:

### Collecting up the values in a range

As you've seen, if you're not using your range object in a for loop, you can, if you want, use collect to obtain all the values from a range object directly:
However, you don't always have to convert ranges to arrays before working on them — you can usually iterate over things directly. For example, you don't have to write this:
because it works just as well (and probably faster) if you leave out the collect:

### Using comprehensions and generators to create arrays

A useful way to create arrays where each element can be produced using a small computation is to use comprehensions (described in Comprehensions).
For example, to create an array of 5 numbers:
With two iterators, you can easily create a 2D array or matrix:
You can add an if test at the end to filter (keep) values that pass a test:
Generator expressions are similar, and can be used in a similar way:
The advantage of generator expressions is that they generate values when needed, rather than build an array to hold them first.

### Creating and filling an array

There are a number of functions that let you create arrays with specific contents. These can be very useful when you're using 2D arrays as matrices:
- zeros(m, n) creates an array/matrix of zeros with m rows and n columns:
You can specify the type of the zeros if you want:
- ones(m, n) creates an array/matrix of ones with m rows and n columns
- rand(m, n) creates an m-row by n-column matrix full of random numbers:
- rand(range, m, n) creates a matrix full of numbers in the supplied range:
- randn(m, n) creates an m-row by n-column matrix full of normally-distributed random numbers with mean 0 and standard deviation 1.
As well as the zeros, ones functions, there are trues, falses, fill, and fill! functions as well.
The trues and falses functions fill arrays with the Boolean values true or false:
Notice how the result is a BitArray.
You can use fill to create an array with a specific value, i.e. an array of repeating duplicates:
With fill!, the exclamation mark (!) or "bang" is to warn you that you're about to change the contents of an existing array (a useful indication that's adopted throughout Julia).
Let's change an array of falses to trues:
You can use the range function to create vector-like arrays, followed by reshape to change them into 2D arrays:
The result is a 10 by 3 array featuring evenly-spaced numbers between 0 and 100.

#### Repeating elements to fill arrays

A useful function for creating arrays by repeating smaller ones is repeat.
The first option for its syntax is repeat(A, n, m), the source array is repeated by n times in the first dimension (rows), and m times in the second (columns).
You don't have to supply the second dimension, just supply how many rows you want:
The second option specifies the extra columns:
The repeat function also lets you create arrays by duplicating rows and columns of a source array. The inner and outer options determine whether rows and/or columns are repeated. For example, inner = [2, 3] makes an array with two copies of each row and three copies of each column:
By contrast, here's outer = [2,3]:
Note that the latter is equivalent to repeat([1, 2], 2, 3). A more meaningful example of the outer keyword is when it is combined with inner. Here, each element of each line of the initial matrix is line-duplicated and then, each line slice of the resulting matrix is column-triplicated:

### Array constructor

The Array function we saw earlier builds arrays of a specific type for you:
This is uninitialized; the odd-looking numbers are simply the old contents of the memory before it was assigned to hold the new array.

#### Arrays of arrays

It's easy to create an array of arrays. Sometimes you want to specify the original contents:
The Array constructor can also construct an array of arrays:
With the reshape function, you could of course just create a simple array and then change its shape:
The same techniques can be used to create 3D arrays. Here's a 3D array of strings:
Each element is set to 'undefined' — #undef.
The push! function pushes another item onto the back of an array:
or you might want to create them empty:
You can use Vector as an alias for Array:

### Copying arrays

If you have an existing array and want to create another array having the same dimensions, you can use the similar function:
Notice that the array dimensions are copied, but the values aren't, they've been copied from random bits of memory. You can, though, change the type and dimensions anyway, so they don't have to be that similar:
And in any case there's a copy function.

### Matrix operations: using arrays as matrices

In Julia, a 2-D array can be used as a matrix. All the functions available for working on arrays can be used (if the dimensions and contents permit) as matrices.
A quick way of typing a matrix is to separate the elements using spaces (to make rows) and to use semicolons to separate the rows. So:
| julia> [1 0 ; 0 1] 2x2 Array{Int64,2}: 1 0 0 1 | ${\begin{pmatrix}1&0\\0&1\\\end{pmatrix}}$ |
You could also do this:
which takes a standard array and reshapes it to run in two rows and two columns. Notice that the matrix is filled column by column.
If you don't use commas or semicolons:
you'll create a single row array/matrix:
In each case, notice the 2 in the braces ({Int64,2}) following the type value. This indicates a 2-dimensional array.
You can create an array of arrays by sticking two arrays next to each other, like this:
When you omit the comma, you're placing columns next to each and you'll get this:

## Accessing the contents of arrays

To access the elements of an array or matrix, follow the name of the array by the element number in square brackets. Here's a 1D array:
Here's the fifth element:
The first element is index number 1. Julia is one of the languages that starts indexing elements in lists and arrays starting at 1, rather than 0. (And thus it's in the elite company of Matlab, Mathematica, Fortran, Lua, and Smalltalk, while most of the other programming languages are firmly in the opposite camp of 0-based indexers.)
The last element is referred to as end (not -1, as in some other languages):
Similarly, you can access the second to last element with
(with similar syntax for the third to last element and so on).
You can provide a bunch of index numbers, enclosed in a pair of brackets at each end:
or supply a range of index numbers:
You can even select elements using true and false values:
Here's a 2D array, with the rows separated by semicolons:
If you just ask for one element of a 2D array, you'll receive it as if the array is unwound column by column, i.e. down first, then across. In this case you'll get 4, not 2:
Asking for row then column works as you expect:
which is row 1, column 2. Here's row 1, column 3:
but don't get the row/column indices the wrong way round:
By the way, there's an alternative way of obtaining elements from arrays: the getindex function:
Use the colon to indicate every row or column. For example, here's "every row, second column":
and here's "second row, every column":

### Elementwise and vectorized operations

Many Julia functions and operators are designed specifically to work with arrays. This means that you don't always have to work through an array and process each element individually.
A simple example is the use of the basic arithmetic operators. These can be used directly on an array if the other argument is a single value:
and every element of the new array is the original multiplied by 2. Similarly:
and every element of the new array is the original divided by 100.
These operations are described as operating elementwise.
Many operators can be used preceded with a dot (.). These versions are the same as their non-dotted versions, and work on the arrays element by element. For example, the multiply function (*) can be used elementwise, using .*. This lets you multiply arrays or ranges together element by element:
and the first element of the result is what you get by multiplying the first elements of the two arrays, and so on.
As well as the arithmetic operators, some of the comparison operators also have elementwise versions. For example, instead of using == in a loop to compare two arrays, use .==. Here are two arrays of ten numbers, one sequential, the other disordered, and an elementwise comparison to see how many elements of array b happened to end up in the same place as array a:

#### Broadcasting: dot syntax for vectorizing functions

This technique of applying functions elementwise to arrays with the dot syntax is called broadcasting. Follow the function name with a dot/period before the opening parenthesis, and supply an array or range as an argument. For example, here's a simple function which multiplies two numbers together:
It works as expected on two scalars:
But it's easy to apply this function to an array. Just use the dot syntax:
In the first example, Julia automatically treated the second argument as if it was an array, so that the multiplication would work correctly.
Watch out for this when combining ranges and vectorized functions:
The first example is equivalent to 0:(10 .* 0.5), and you might have intended (0:10) .* 0.5.

### min and max

Watch out for max and min. You might think that max can be used on an array, like this, to find the largest element:
but no…
The max function returns the largest of its arguments. To find the largest element in an array, you can use the related function maximum:
You can use max on two or more arrays to carry out an elementwise examination, returning another array containing the maximum values:
min and minimum behave in a similar way.
A way to make max work on an array is to use the ellipsis (splat) operator:
You can test each value of an array and change it in a single operation, using element-wise operators. Here's an array of random integers from 0 to 10:
Now you can test each value for being equal to 0, then set only those elements to 11, like this:
This works because a .== 0 returns an array of true and false values, and these are then used to select the elements of a which are to be set to 11.
If you're doing arithmetic on 2D matrices, you might want to read more about matrix arithmetic: Matrix arithmetic

### Rows and Columns

With a 2D array, you use brackets, colons, and commas to extract individual rows and columns or ranges of rows and columns.
With this table:
you can find a single row using the following (notice the comma):
and you can get a range of rows with a range followed by a comma and a colon:
To select columns, start with a colon followed by a comma:
On its own, the colon accesses the entire array:
To extract a range of columns:

### Finding items in arrays

If you want to know whether an array contains an item, use the in function, which can be called in two ways:
Or phrased as a function call:
There's a set of functions starting with find — such as findall, findfirst, findnext, findprev and findlast — that you can use to get the index or indices of array cells that match a specific value, or pass a test. Each of these has two or more more forms.
Here's an array of small primes:
To find the first occurrence of a number, and obtain its index, you can use the following method of the findfirst function:
so the first occurrence of 13 in the array is in the sixth cell:
This function is similar to many in Julia which accepts a function as the first argument. The function is applied to each element of an array, and if the function returns true, that element or its index is returned. This function returns the index of the first element.
Here's another example using an anonymous function:
The findall function returns an array of indices, pointing to every element where the function returns true when applied:
Remember that these are arrays of index numbers, not the actual cell values. The indices can be used to extract the corresponding values using the standard square bracket syntax:
whereas findfirst returns a single number — the index of the first matching cell:
The findnext function is very similar to the findall and findfirst functions, but accepts an additional number that tells the functions to start the search from somewhere in the middle of the array, rather than from the beginning. For example, if findfirst(smallprimes,13) finds the index of the first occurrence of the number 13 in the array, we can continue the search from there by using this value in findnext:
To return the indices of the elements in array B where the elements of array A can be found, use findall(in(A), B):
The order in which the indices are returned should be noted.

#### Finding out about an array

With our 2D array:
we can find out more about it using the following functions:
* ndims
* size
* length
* count
ndims returns the number of dimensions, i.e. 1 for a vector, 2 for a table, and so on:
size returns the row and column count of the array, in the form of a tuple:
length tells you how many elements the array contains:
You can use count to find out how many times a particular value occurs. For example, how many non-zero items are there?
For finding the inverse, determinant and other aspects of an array/matrix, see Manipulating matrices.
To convert between index numbers (1 to n) and row/column numbers (1:r, 1:c), you can use:
to find the row and column for the sixth element, for example.
And to go in the other direction, what index number corresponds to row3, column 2? Use the opposite of Cartesian indices, Linear indices:
diff is useful to find the differences between each element of an array:

#### Comparing arrays

union builds a new array that's the union or combination of two or more arrays. The operation removes duplicates, and the result contains a single version of each element:
Notice that the ordering of the new union reflects the original order. This example doesn't sort the numbers at all:
intersect returns a new array that's the intersection of two or more arrays. The result contains one occurrence of each element, but only if it occurs in every array:
setdiff finds the difference between two arrays, i.e. the elements that are in the first array but not the second:

#### Filtering

There's a set of related functions that let you work on an array's elements.
filter finds and keeps elements if they pass a test. Here, we're using the isodd function (passing it as a named function without parentheses, rather than a function call with parentheses) to filter (keep) everything in the array that's odd.
Like many Julia functions, there's a version which changes the array. So filter returns a copy of the original, but filter! changes the array.
The count function we met earlier is like filter, but just counts the number of elements that satisfy the condition:
Also, the any function just tells you whether any of the elements satisfy the condition:
and the all function tells you if all of the elements satisfy the condition. Here, all checks to see whether filter did the job properly.

#### Random element of an array

To choose a random element from an array:

#### Other functions

Because arrays are fundamental to Julia, there are dozens of array-handling functions that can't be described here. But here are a few selections:
Find the extreme values of an array:
findmax finds the maximum element and returns it and its index in a tuple:
Use argmax to return just the index.
The maximum and minimum functions let you supply functions to determine how the "maximum" is determined. This is useful if your arrays are not simple vectors. This example find the maximum array element, where maximum here means, "has the largest last value":
Functions such as sum, prod, mean, middle, do what you would expect:
(mean and middle have been moved into the Statistics module in the standard library; you may need to first enter "using Statistics" to use them)
sum, mean, and prod also let you supply functions: the function is applied to each element and then the results are summed/mean-ed/prod-ded:
There are functions in the Combinatorics.jl package that let you find combinations and permutations of arrays. combinations finds all the possible combinations of elements in an array: you can specify how many elements in each combination:
and permutations generates all permutations. There are a lot — in practice you probably won't need to use collect to collect the items into an array:

## Modifying array contents: adding and removing elements

To add an item at the end of an array, use push!:
As usual, the exclamation mark reminds you that this function changes the array. You can push only onto the end of vectors.
To add an item at the front, use pushfirst!:
To insert an element into an array at a given index, use the splice! function. For example, here's a list of numbers with an obvious omission:
Use splice! to insert a sequence at a specific range of index values. Julia returns the values that were replaced. The array grows larger to accommodate the new elements, and elements after the inserted sequence are pushed down. Let's insert, at position 4:5, the range of numbers 4:6:
You'll be tempted to check that the new values were inserted correctly:
Now, if you want to insert some values at a specific inter-index location, you will have to use a feature known as empty ranges. In this case the interspace between indexes n-1 and n is denoted as n:n-1.
For example:

### Removing elements

If you don't supply a replacement, you can also use splice! can remove elements and move the rest of them along.
To remove the last item:
and the first:
More aggressive modification of arrays (and similar data structures) can be made with functions such as deleteat! and splice!. You can find out the indices of elements in various ways. Once you know the indices, you can use deleteat! to delete an element, given its index number:
deleteat! also accepts a range or iterator to specify the indices, so you can do this:
Remember that you can always remove a group of elements using a filter: see Filtering.

### Other functions

If you want to do something to an array, there's probably a function to do it, and sometimes with an exclamation mark to remind you of the potential consequences. Here are a few more of these array-modifying functions:
* resize! change the length of a Vector
* append! push a second collection at the back of the first one
* prepend! insert elements at the beginning of the first Vector
* empty!(a) remove all elements
* unique(a) remove duplicate elements from the array "a" without overwriting the array.
* unique!(a) remove duplicate elements from the array "a" and overwrites the array.
* rotr90(a) make a copy of an array rotated 90 degrees clockwise:
* circshift(a) move the elements around 'in a circle' by a number of steps:
This function can also do circular shifts on 2D arrays too. For example, here's a table:
By supplying a tuple you can move rows and columns. For example: moving the columns by 0 and the rows by 1 moves the first dimension by 0 and the second by 1. The first dimension is downwards, the second rightwards:
There's a modifying version of circshift, circshift!

### Setting the contents of arrays

To set the contents of an array, specify the indices on the left-hand side of an assignment expression:
To check that the array has really changed:
You can set a bunch of elements at the same time, using the broadcasting assignment operator:
And you can set a sequence of elements to a suitable sequence of values:
Notice here that, although Julia shows the 7 element slice as the return value, in fact the whole array has been modified:
You can set ranges to a single value in one operation using broadcasting:
As an alternative to the square bracket notation, there's a function call version that does the same job of setting array contents, setindex!:
You can refer to the entire contents of an array using the colon separator without start and end index numbers, i.e. [:]. For example, after creating the array a:
we can refer to the contents of this array a using a[:]:

### Passing arrays to functions

A function can't modify a variable passed to it as an argument, but it can change the contents of a container passed to it.
Consider the following function, that changes its argument to 5:
Although the x inside the function is changed, the x outside the function isn't. Variable names in functions are local to the function.
But, you can modify the contents of a container, such as an array. The next function uses the [:] syntax to access the contents of the container x, rather than change the value of the variable x:
If, instead of accessing the container variable's contents, you try to change the variable itself, it won't work. For example, the following function definition creates an array of 5s in temp and then attempts to change the argument x to be temp.
It looks like it worked, but:
You can change elements of the array, but you can't change the variable so that it points to a different array. In other words, your function isn't allowed to change the binding between the argument and the array that was passed to it.
Julia's way of handling function arguments is described as “pass-by-sharing”. An array isn't copied when you pass it to a function (that would be very inefficient for large arrays).

### Matrix arithmetic

For matrix-on-matrix arithmetic action, you can:
- add (+) and subtract (-):
| julia> A = reshape(1:12, 3, 4) 3x4 Array{Int64,2}: 1 4 7 10 2 5 8 11 3 6 9 12 | ${\begin{pmatrix}1&4&7&10\\2&5&8&11\\3&6&9&12\\\end{pmatrix}}$ |
| julia> B = ones(3,4) 3x4 Array{Float64,2}: 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 | ${\begin{pmatrix}1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\\end{pmatrix}}$ |
| julia> A + B 3x4 Array{Float64,2}: 2.0 5.0 8.0 11.0 3.0 6.0 9.0 12.0 4.0 7.0 10.0 13.0 | ${\begin{pmatrix}1&4&7&10\\2&5&8&11\\3&6&9&12\\\end{pmatrix}}+{\begin{pmatrix}1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\\end{pmatrix}}={\begin{pmatrix}2.0&5.0&8.0&11.0\\3.0&6.0&9.0&12.0\\4.0&7.0&10.0&13.0\\\end{pmatrix}}$ |
| julia> A - B 3x4 Array{Float64,2}: 0.0 3.0 6.0 9.0 1.0 4.0 7.0 10.0 2.0 5.0 8.0 11.0 | ${\begin{pmatrix}1&4&7&10\\2&5&8&11\\3&6&9&12\\\end{pmatrix}}-{\begin{pmatrix}1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\1.0&1.0&1.0&1.0\\\end{pmatrix}}={\begin{pmatrix}0.0&3.0&6.0&9.0\\1.0&4.0&7.0&10.0\\2.0&5.0&8.0&11.0\\\end{pmatrix}}$ |
- multiply (*), assuming the dimensions are compatible, so m1 * m2 is possible if last(size(m1)) == first(size(m2)). Note the difference between matrix multiplication and elementwise matrix multiplication. Here's a matrix A:
| julia> A = [1 2 ; 3 4] 2x2 Array{Int64,2}: 1 2 3 4 | ${\begin{pmatrix}1&2\\3&4\\\end{pmatrix}}$ |
and here's matrix B:
| julia> B = [10 11 ; 12 13] 2x2 Array{Int64,2}: 10 11 12 13 | ${\begin{pmatrix}10&11\\12&13\\\end{pmatrix}}$ |
The .* broadcasting operator multiplies them elementwise:
| julia> A .* B 2x2 Array{Int64,2}: 10 22 36 52 | ${\begin{pmatrix}1&2\\3&4\\\end{pmatrix}}.*{\begin{pmatrix}10&11\\12&13\\\end{pmatrix}}={\begin{pmatrix}10&22\\36&52\\\end{pmatrix}}$ |
Compare this with matrix multiplication, A * B:
| julia> A * B 2x2 Array{Int64,2}: 34 37 78 85 | ${\begin{pmatrix}1&2\\3&4\\\end{pmatrix}}\times {\begin{pmatrix}10&11\\12&13\\\end{pmatrix}}={\begin{pmatrix}34&37\\78&85\\\end{pmatrix}}$ |
which is:
- division of two matrices. You can use the backslash (\) for left division:
and the forward slash (/) right or slash division:
With a matrix and a scalar, you can add, subtract, multiply, and divide:
and more besides:
You can multiply matrix and a vector (the matrix-vector product), if the arrays have compatible shapes. Here's the matrix A:
| julia> A = reshape(1:12, 3, 4) 3x4 Array{Int64,2}: 1 4 7 10 2 5 8 11 3 6 9 12 | ${\begin{pmatrix}1&4&7&10\\2&5&8&11\\3&6&9&12\\\end{pmatrix}}$ |
and here's a vector V:
| julia> V = collect(1:4) 4-element Array{Int64,1}: 1 2 3 4 | ${\begin{pmatrix}1\\2\\3\\4\\\end{pmatrix}}$ |
The * operator multiplies them:
| julia> A * V 3-element Array{Int64,1}: 70 80 90 | ${\begin{pmatrix}1&4&7&10\\2&5&8&11\\3&6&9&12\\\end{pmatrix}}*{\begin{pmatrix}1\\2\\3\\4\\\end{pmatrix}}={\begin{pmatrix}70\\80\\90\\\end{pmatrix}}$ |
The dot or inner product (aTb) can be found using the dot function, but you'll have to import the LinearAlgebra library first:
| julia> dot([1:3...], [21:23...]) 134 | ${\begin{pmatrix}1&2&3\\\end{pmatrix}}\cdot {\begin{pmatrix}21&22&23\\\end{pmatrix}}=134$ |
The two arguments must have the same length. You can also use the dot operator, which you can obtain in the REPL by typing "\cdot" followed by a tab:

### Joining arrays and matrices

You can use hcat and vcat to join matrices together, if their dimensions permit.
hcat keeps the first dimension and extends (joins) in the second, vcat keeps the second dimension and extends the first.
Here are two 3 by 4 matrices:
hcat(A, B) makes a new array that still has 3 rows, but extends/joins the columns to make 8 in total:
vcat(A, B) makes a new array that keeps the 4 columns, but extends to 6 rows:
You'll probably find the shortcuts useful:
* [A ; B ] is vcat(A, B)
* [A B ] is hcat(A, B)
vec flattens a matrix into a vector, turning it into a (what some call a 'column') vector:
There's also an hvcat function ([A B; C D;]) that does both.
You can use hcat to convert an array of arrays to a matrix (using the hcat-splat):
Julia arrays are 'column-major'. This means that you read down the columns:
whereas 'row-major' arrays are to be read across, like this:
Column-major order is used in Fortran, R, Matlab, GNU Octave, and by the BLAS and LAPACK engines (the "bread and butter of high-performance numerical computation"). Row-major order is used in C/C++, Mathematica, Pascal, Python, C#/CLI/.Net and others.

### Growing or extending arrays

Often you want to create an array and then add more to it, or 'grow' it. While can do this with vcat and hcat, be aware that both these operations create new temporary arrays and copy elements, so they don't always produce the fastest code. A better way is to use push!. This is an efficient operation that extends the array. You can reshape the array later:
reshape lets you change the dimensions of an array. You can supply the dimensions or use a colon (:) to ask Julia to calculate valid dimensions:
reshape(a, (10, div(length(a), 10))) would have the same effect.
push! doesn't let you push new rows to a 2D array or matrix. The best way to do the job is to work on a 1D array, as above, adding more elements at the end, and then use reshape to convert it to two dimensions. If necessary, use transpose to flip the matrix.

### Manipulating matrices

To transpose an array or matrix, there's an equivalent ' operator for the transpose function, to swap rows and columns:
To find the determinant of a square matrix, use det, after remembering to load the LinearAlgebra library.
inv (in the Standard Library) finds the inverse of a square matrix, if it has one. (If the determinant of the matrix is zero, it won't have an inverse.)
LinearAlgebra.rank finds the rank of the matrix, and LinearAlgebra.nullspace finds the basis for the nullspace.
LinearAlgebra.tr sums the diagonal of a square matrix (trace):

### Applying functions to matrices

There are a number of functions that can be applied to a matrix:
- sum adds every element:
You can specify a dimension if you want to sum just columns or rows. So to sum columns, specify dimension 1:
To sum rows, specify dimension 2:
- mean finds the mean of the values in the matrix:
As with sum, you can specify a dimension, so that you can find the mean of columns (use dimension 1) or rows (use dimension 2):
- the min.(A, B) and max.(A, B) functions compare two (or more) arrays element by element, returning a new array with the largest (or smallest) values from each:
prod multiplies a matrix's elements together:
(Notice the use of BigInt, products are very large.)
You can specify a dimension if you want to multiply just columns or rows. To multiply the elements of columns together, specify dimension 1; for rows, use dimension 2:

### Matrix norms

Most of these functions live in the LinearAlgebra library:

#### Vector norms

The Euclidean norm, $\|x\|_{2}={\sqrt {x_{1}^{2}+x_{2}^{2}+\ldots +x_{n}^{2}}}$, is found by LinearAlgebra.norm(x):
If X is a 'row' vector:
The Euclidean distance between vectors $x$ and $y$, given by $\|x-y\|_{2}$, is found by norm(x - y):
The angle between two vectors $a$ and $b$ is $\arccos \left({\frac {a^{T}b}{\|a\|_{2}\|b\|_{2}}}\right)$:

#### Matrix norms

Here's the 1-norm of a matrix (the maximum absolute column sum):
And here's the infinity norm (the maximum absolute row sum):
Note they are different from vectorized 1-norm or infinity norm:
The Euclidean norm is the default:

### Scaling and rotating matrices

- rmul!(A, n) scales every element of the matrix in place by a scale factor n:
There are rotation and circular-shifting functions too:
reverse makes a copy of a matrix reversing rows or columns:
squeeze and reshape can be used to change the dimensions of a matrix. For example, this is how you can use squeeze to collapse a row vector (1 by 4) into a 4 by 1 array:

### Sorting arrays

Julia has a flexible sort function that returns a sorted copy of an array, and a companion sort! version that changes the array so that it's sorted.
You can usually use sort without options and obtain the results you'd hoped for:
You can sort 2D arrays:
although there are more powerful alternatives in sortrows and sortcolumns — see below for details.
The sortperm function is similar to sort, but it doesn't return a sorted copy of the collection. Instead it returns a list of indices that could be applied to the collection to produce a sorted version:

#### Sort by and comparisons

If you need more than the default sort offers, use the by and lt keywords and provide your own functions for processing and comparing elements during the sort.

##### sort by

The by function processes each element before comparison and provides the 'key' for the sort. A typical example is the task of sorting a list of numbers in string form into numerical order. Here's the list:
If you use the default sort, the numbers appear in the order in which the characters appear in Unicode/ASCII:
with "1E-10" appearing after "0.999".
To sort the numbers by their value, pass the parse function (from the Meta package) to by:
The strings are sorted 'by' their value. Notice that the by function you supply produces the numerical sort key, but the original string elements appear in the final result.
Anonymous functions can be useful when sorting arrays. Here's a 10 rows by 2 columns array of tuples:
You can sort this array by the second element of each tuple, not the first, by supplying an anonymous function to by that points to the second element of each. The anonymous function says, given an object x to sort, sort by the second element of x:

##### Sorting by multiple columns

You can supply a tuple of "column" identifiers in the by function, if you want to sort by more than one column.
This sorts the array first by column 1, then by column 2, then by column 3.

##### Redefining 'less than'

By default, sorting uses the built-in isless function when comparing elements. In a sorted array, the first element is less than the second.
You can change this behaviour by passing a different function to the lt keyword. This function should compare two elements and return true if they're sorted, i.e. if the first element is 'less than' the second, using some definition of 'less than'. The sorting process compares pairs of elements repeatedly until every element of the array is in the right place.
For example, suppose you want to sort an array of words according to the number of vowels in each word; i.e. the more vowels a word has, the earlier in the sorted results it occurs. For example, the word "orange" will be considered to be "less than" the word "lemon", because it has more vowels.
First we'll need a function that counts vowels:
Now you can pass an anonymous function to sort that compares the vowel count of two elements using this function and then returns the element with a higher count in each case:
The result is that the word with the most vowels appears first:
The sort function also lets you specify a reverse sort - after the by and lt functions (if used) have done their work, a true value passed to rev reverses the result.

#### Sorting 2-D arrays

In Julia 1.0, you can sort multidimensional arrays with sortslices.
Here's a simple array of nine strings (you can also use numbers, symbols, functions, or anything that can be compared):
You supply a number or a tuple to the dims ("dimensions") keyword that indicates what you want to sort. To sort the table so that the first column is sorted, use 1:
Note that sortslices returns a new array. The first column is in alphabetical order.
Use dims=2 to sort the table so that the first row is sorted:
Now the first row is in alphabetical order.
If you want to sort by something other than the first item, pass a function to by. So, to sort rows so that the middle column is in alphabetical order, use:
sortslices has most of the options that you'll find in sort, and more besides. You can reverse the order with rev, change the comparator with lt, and so on.

## Tuples

A tuple is an ordered sequence of elements, like an array. A tuple is represented by parentheses and commas, rather than the square brackets used by arrays. Tuples are mostly good for small fixed-length collections — they're used everywhere in Julia, for example, as argument lists and for returning multiple values from functions.
The important difference between arrays and tuples is that tuples are immutable. Other than that, tuples work in much the same way as arrays, and many array functions can be used on tuples too:
You can have two-dimensional tuples:
But you can't change a tuple:
And, because you can't modify tuples, you can't use any of the functions like push! that you use with arrays:

### Named tuples

A named tuple is like a combination of a tuple and a dictionary. Like a tuple, a named tuple is ordered and immutable, and enclosed in parentheses; like a dictionary, each element has a unique key that can be used to access it.
You can create a named tuple by providing keys and values directly:
To access the values, use the familiar dot syntax:
You can access all the values (destructuring) as with ordinary tuples:
or just some of them:
Elements can be the same type, or different types, but the keys will always be variable names.
You can iterate over a named tuple:
Another way to create a named tuple is to provide the keys and values in separate tuples:
You can combine two named tuples to make a new one:
You can use existing variables for keys:
Making single value Named Tuples requires a strategically-placed comma:
If you forget it, you'll see this:
You can make new named tuples by combining named tuples together.
Use a comma after a single element named tuple:
because without the comma, the tuple will be interpreted as a parenthesized keyword argument to merge.
To iterate over the "keys", use the fieldnames and typeof functions:
so you can do:
Merging two tuples is done intelligently. For example, if you have this named tuple:
and you want to add a center point and change the top color:
the new value is inserted, and the existing value is changed.

#### Using named tuples as keyword arguments

A named tuple is a convenient way to pass a group of keyword arguments to a function. Here's a function that accepts three keyword arguments:
You can define a named tuple that contains the names and values for one or more keywords:
To pass the named tuple to the function, use the ; when you call the function:
If you specify a keyword and value, it can be overridden by a later definition: