Fill an array with specific values in Julia | Array fill() method
The fill() is an inbuilt function in julia which is used to return an array of specified dimensions filled with a specific value passed to it as parameter.
Syntax: fill(Value, Dimension)
Parameters:
- Value: To be filled in the array
- Dimension: Required size of the array
Returns: It returns an array of nXn dimension with each element as the specified value.
Example:
Python
# Julia program to illustrate # the use of Array fill() method # Creating a 1D array of size 4 # with each element filled with value 5 A = fill( 5 , 4 ) println(A) # Creating a 2D array of size 2X3 # with each element filled with value 5 B = fill( 5 , ( 2 , 3 )) println(B) # Creating a 3D array of size 2X2X2 # with each element filled with value 5 C = fill( 5 , ( 2 , 2 , 2 )) println(C) |
Output:
Array fill!() method
fill!() method works exactly like fill() method i.e. it fills an array with a specific value passed to it as argument, but the only difference is that, fill!() method takes an existing array as argument and fills it with a new specified value. While the fill() method takes array dimensions and creates a new array of its own.
Syntax: fill!(Array, Value)
Parameters:
- Array: It is the array of specified dimension.
- Value: It is the value to be filled in the array.
Returns: It returns the array passed to it as argument with the specified value filled at each index.
Example: Below code is using one dimension array of 3 elements.
Python
# Julia program to illustrate # the use of Array fill() method # Creating a 1D array of size 5 Array1 = [ 1 , 2 , 3 , 4 , 5 ] # Filling array with fill!() Array1 = fill!(Array1, 10 ) println(Array1) # Creating a 2D array of size 2X2 Array2 = [ 1 2 ; 3 4 ] Array2 = fill!(Array2, 10 ) println(Array2) # Creating a 3D array of size 2X2X2 Array3 = cat([ 1 2 ; 3 4 ], [ 5 , 6 ; 7 8 ], dims = 3 ) Array3 = fill!(Array3, 10 ) println(Array3) |
Output:
Please Login to comment...