0

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.

Justin
  • 24,288
  • 12
  • 92
  • 142
ChrlTsr
  • 149
  • 1
  • 7

2 Answers2

3

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

mu7z
  • 466
  • 5
  • 14
0

The first definition works also with:

map(gtest2, x)

or

gtest2.(x)
elsuizo
  • 144
  • 1
  • 3