# Alternative way to create following array raised to powers?

**URL:** https://discourse.julialang.org/t/alternative-way-to-create-following-array-raised-to-powers/74154
**Category:** New to Julia
**Tags:** matrices
**Created:** [January 6, 2022, 5:32pm UTC](https://discourse.julialang.org/t/alternative-way-to-create-following-array-raised-to-powers/74154 "2022-01-06T17:32:07Z")
**Posts on this page:** 1
**Showing post:** 9

<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: [January 6, 2022, 8:05pm UTC](https://discourse.julialang.org/t/alternative-way-to-create-following-array-raised-to-powers/74154/9 "2022-01-06T20:05:16Z")

</div>

> [@yewalenikhil65](#):
>
> How to do following more efficiently (any alternative way ?)

What you are constructing is a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix) (transposed). A much faster way to construct it is to use two nested loops, as described in [another discourse thread](https://discourse.julialang.org/t/efficient-creation-of-power-series-matrix-or-array-of-arrays/18988/7).

The two-loop approach is about 30x faster on my machine for constructing a 100x100 Vandermonde matrix, compared to the broadcasting approach suggested above:

```julia
julia> using BenchmarkTools

julia> vander(x, n=length(x)) = .... # two-loop version from discourse

julia> bvander(x, n=length(x)) = x .^ (0:n-1)'; # broadcast-based vandermonde

julia> x = rand(100);

julia> @btime vander($x);
  5.892 μs (2 allocations: 78.17 KiB)

julia> @btime bvander($x);
  193.366 μs (2 allocations: 78.17 KiB)

```

The reason the two-loop version can be so much faster is that it doesn’t compute each power separately, but instead accumulates the powers one multiplication at a time from the previous powers.

(The broadcasting version is much more compact, though, so if it’s not too performance-critical I would stick with that!)

Another option is to create the matrix lazily, e.g. [SpecialMatrices](https://github.com/JuliaMatrices/SpecialMatrices.jl) has methods to implicitly create such matrices and work with them. The main advantage here is that if you are doing things like solving linear systems, there are specialized algorithms for Vandermonde matrices.

---

_[View the full topic](https://discourse.julialang.org/t/alternative-way-to-create-following-array-raised-to-powers/74154)._
