Reputation: 149
I am trying to plot a function using PyPlot on an IJulia notebook, but I keep obtaining error messages.
When I ran this code:
function gtest2(x)
6.34*(log2(1+exp(10.0*(x+0.5))))^0.8
end
using PyPlot
x = -1.0:0.1:1.0;
plot(x, gtest2(x));
I got errors like these:
MethodError: no method matching ^(::Array{Float64,1}, ::Float64) Closest candidates are: ^(::Float64, ::Float64) at math.jl:355 ...
I tried to defined a different type of variable while defining my function using gtest2(x::Number)
or gtest2(x::Float64)
but I have the same errors.
It does the same using linespace
instead of -1.0:0.1:1.0
. I understand that the format the function sees in input does not match the definition but I don't get what I'm doing wrong because simple functions work:
function f(x)
x
end
plot(x,f(x))
Why am I getting those errors in the first case?
I am using IJulia notebook 0.5.1 on safari.
Upvotes: 0
Views: 97
Reputation: 506
Your code doesn't properly handle vectors thus you need to either change gtest
using the .
vectorization syntax
function gtest2(x)
6.34*(log2.(1 + exp.(10.0*(x + 0.5)))).^0.8
end
or even easier use the dot vectorization as follows
plot(x, gtest2.(x));
To learn more about dot vectorization please see the following in the docs: https://docs.julialang.org/en/latest/manual/functions.html#man-vectorized-1
Upvotes: 3