Broadcasting across arrays in Julia
Julia is a high performance, dynamic programming language that has a high-level syntax. It is free for everyone to use and easy to learn. Julia is used generally for data analysis and visualization purposes.
A grid that contains objects in multiple dimensions is called a Multi-dimensional Array. It can contain any type of object but for most computational purposes Int or Float type objects must be present. It is comparatively easier to implement Arrays in Julia than other computational languages. Arrays can be written in the code in an understandable manner and the compiler takes care of the implementation which is performance and time-efficient. In Julia, a custom array type can also be defined by inheriting from AbstractArray.
Broadcasting across Arrays
Sometimes it is very useful to apply operations on only some elements of an array, like adding a vector of two elements to the array. But it can be inefficient if it is done by increasing the size of the vector to the array’s size, especially for arrays with a large number of elements and more dimensions.
To tackle this problem, Julia provides the broadcast() function which increases the size of a singleton dimension array to the array we want to operate on and applies the function we provide, without using any extra memory. Hence, for large arrays, memory is not wasted. The function is valid not only for arrays but other structures too.
The arguments we can pass in the broadcast() function are as follows:
- Array to be added
- Array to be added on
Applying the function on a 1D array:
Applying the function on a 2D array:
Applying the function on a 3D array:
Using dot operator
We can use the dot operator (.+, .-, .*, .=) to implement the same operations we did with the broadcast() function
Using the dot operator on a 1D array:
Using the dot operator on a 2D array:
Using the dot operator on a 3D array:
Julia provides us with many functions that can broadcast on arrays, applying various operations. And we can implement these functions using the dot operator as shown below.