# How to plot a function returns multiple values?

Now I have a function:

``````function f(x)
return sin(x),cos(x),tan(x)
end
``````

that reruns multiple values, sin(x),cos(x),tan(x).
I want to plot each value:

``````xs = range(-π,π,length = 10)
plot(xs,f.(xs))
plot(xs,f.(xs))
plot(xs,f.(xs))
``````

And I get the error `x and y must have same first dimension`
How can I plot each return value?

Here is one option:

``````xs = range(-π, π, length = 10)
fxs = f.(xs) # gives a vector of tuples
fxs1 = [x for x in fxs] # extract each component
fxs2 = [x for x in fxs]
fxs3 = [x for x in fxs]
plot(xs, fxs1)
plot(xs, fxs2)
plot(xs, fxs3)
``````
5 Likes

Thank you very much!

Here is another way:

``````xs = range(-π,π,length = 100)
ys = hcat(collect.(f.(xs))...)
plot(xs,ys', ylims=(-2,2))
``````

NB:
the function can simply be written as:
`f(x) = sin(x),cos(x),tan(x)`

1 Like

A quick comment: you shouldn’t evaluate `f` 3 times like you did (it can be super expensive)! Have a look at the answers to see how you can evaluate `f` once and store the result.

4 Likes

An encrypted one liner:

``````f(x) = sin(x), cos(x), tan(x)
xs = range(-π, π, length = 100)
plot(xs, reduce(vcat, reduce.(hcat,f.(xs))), ylims=(-2,2))
``````

which plots a 100-by-3 matrix against `xs`. 1 Like

For functions returning multiple values, I find the `Unzip` package really useful:

``````using Unzip

f(x) = sin(x),cos(x),tan(x)
xs = range(-π,π,length = 100)
fxs1, fxs2, fxs3 = unzip(f.(xs))
plot( plot(xs, fxs1),
plot(xs, fxs2),
plot(xs, fxs3) )
``````

or:

``````plot(xs, reduce(hcat, unzip(f.(xs))))
``````
3 Likes

Another solution:

``````plot(xs, getindex.(f.(xs), [1 2 3]))
``````
3 Likes