gradient
gradient(F, [h])
Compute differences along vector F
, using h
as the spacing between points. The default spacing is one.
Examples
-
Calculate the gradient of a function:
julia> f(x) = x^2 + 2x + 1; julia> gradient(f, [1, 2, 3]) 3-element Array{Int64,1}: 4 6 8
This example calculates the gradient of the function
f(x) = x^2 + 2x + 1
at the points[1, 2, 3]
. -
Calculate the gradient with a custom spacing:
julia> f(x) = sin(x); julia> gradient(f, [0.0, 0.1, 0.2, 0.3], 0.1) 4-element Array{Float64,1}: 0.9983341664682815 0.49875020878499973 -0.001665833531718474 -0.5012497912150002
It calculates the gradient of the function
f(x) = sin(x)
at the given points[0.0, 0.1, 0.2, 0.3]
using a spacing of0.1
. - Calculate the gradient without specifying the spacing (default spacing):
julia> f(x) = exp(x) + x^2; julia> gradient(f, [1, 2, 3]) 3-element Array{Float64,1}: 4.718281828459045 9.389056098930649 20.085536923187668
It calculates the gradient of the function
f(x) = exp(x) + x^2
at the points[1, 2, 3]
using the default spacing of 1.
Common mistake example:
julia> f(x, y) = x^2 + y^2;
julia> gradient(f, [1, 2, 3])
ERROR: MethodError: no method matching gradient(::typeof(f), ::Array{Int64,1})
In this example, the function f(x, y)
is defined with two arguments, but the gradient
function is called with only one array argument. Ensure that the function passed to gradient
matches the number of elements in the array or provide the correct number of arguments for the function.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.