# Why the function nroots returns a Matrix{Array{Int64,0}}

**URL:** https://discourse.julialang.org/t/why-the-function-nroots-returns-a-matrix-array-int64-0/105167
**Category:** General Usage
**Tags:** question
**Created:** [October 19, 2023, 9:36am UTC](https://discourse.julialang.org/t/why-the-function-nroots-returns-a-matrix-array-int64-0/105167 "2023-10-19T09:36:37Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [October 19, 2023, 1:17pm UTC](https://discourse.julialang.org/t/why-the-function-nroots-returns-a-matrix-array-int64-0/105167/3 "2023-10-19T13:17:44Z")

</div>

Note that this is a continuation of this thread: [How to convert a Matrix{Array{Int64, 0}} to a Matrix{Int64}](https://discourse.julialang.org/t/how-to-convert-a-matrix-array-int64-0-to-a-matrix-int64/105136)

> [@empet](#):
>
> ```julia-auto
> function nroots!(p, z; eps=1e-05, maxiter=50)
> dp= derivative(p)
> ddp=derivative(dp)
> prod=ddp*p 
> nr=zeros(Int, size(z)) 
> 
> ```

You wrote your `nroots!` function in a classic Matlab-ish “vectorized” style where it assumes that `z` is an array, and allocates the result `nr` as an array too. If `z` is a scalar, then `size(z) = ()` and `nr` is a zero-dimensional array (which is _not_ the same thing as a scalar in Julia).

In this case, it doesn’t seem like there is any advantage in a vectorized style — even if `z` is an array, the different z’s don’t seem to share any computation. I would suggest just writing a function that works for scalar `z` and then broadcasting it as needed. If I understand your code correctly, this should be:

```julia-auto
function nroots(p, z; eps=1e-05, maxiter=50)
   dp= derivative(p)
   ddp=derivative(dp)
   prod=ddp*p 
   nr=0
   for _ in 1:maxiter 
       z, zprev= z-p(z)/(dp(z) - prod(z)/(2*dp(z))), z
       nr += abs(z-zprev)^2 > eps
   end 
   return nr 
end 

```

(Note that neither this nor your original `nroots!` function should end with a `!`, by Julia convention, since neither of them mutate their arguments. Reassigning `z` is [not mutation](https://docs.julialang.org/en/v1/manual/variables/#man-assignment-expressions).)

Then you can broadcast this as `nr = nroots.(p, z)` over an array `z` and it will return an array of scalars.

---

_[View the full topic](https://discourse.julialang.org/t/why-the-function-nroots-returns-a-matrix-array-int64-0/105167)._
