Why does [1:3] .^ 3 not work?

Hi,

I’m a long time Matlab user trying to make the transition to Julia. It wasn’t obvious from reading the documentation whether the following behavior was a bug or just a characteristic of the language.

The following code throws an error, reporting no matching method in Julia 1.6.3

A = 1:10
B = A.^3

Is there a Julia-esque way to perform this operation or is this a bug?

Works for me in 1.6.1. Can you show your full session?


julia> A = 1:10
1:10

julia> B = A.^3
10-element Vector{Int64}:
    1
    8
   27
   64
  125
  216
  343
  512
  729
 1000

3 Likes

Looks like my Matlab habits bit me. I’m used to [1:10] being equivalent to 1:10.

Definitely not the case in Julia, the brackets create a Vector{UnitRange{Int64}}. Thanks for the sanity check!

1 Like

in MATLAB, a scalar is a 1x1 matrix so there’s no scalar.

In Julia you could splat the range element of the vector to make it work:

julia> [1:3...].^3
3-element Vector{Int64}:
  1
  8
 27
2 Likes

While that works, it will be very inefficient for large ranges. It’s usually more idiomatic to write this as [1:3;].^3 instead.

7 Likes

But why? Why not just (1:3).^3?

6 Likes

Yeah, that might not have been a particularly good example. I just meant that if you really want to collect a range into a mutable vector for whatever reason that would be the preferable way to do it.

4 Likes