• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / 1261

06 Sep 2025 02:48AM UTC coverage: 77.416% (+0.2%) from 77.205%
1261

push

buildkite

web-flow
Add `--trace-eval` and `Base.TRACE_EVAL` for showing each top level eval (#57137)

5 of 15 new or added lines in 1 file covered. (33.33%)

177 existing lines in 14 files now uncovered.

61666 of 79655 relevant lines covered (77.42%)

22329079.09 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.71
/base/abstractarraymath.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
 ## Basic functions ##
4

5
isreal(x::AbstractArray) = all(isreal,x)
4,027✔
6
iszero(x::AbstractArray) = all(iszero,x)
38,760✔
7
isreal(x::AbstractArray{<:Real}) = true
×
8

9
## Constructors ##
10

11
"""
12
    vec(a::AbstractArray)::AbstractVector
13

14
Reshape the array `a` as a one-dimensional column vector. Return `a` if it is
15
already an `AbstractVector`. The resulting array
16
shares the same underlying data as `a`, so it will only be mutable if `a` is
17
mutable, in which case modifying one will also modify the other.
18

19
# Examples
20
```jldoctest
21
julia> a = [1 2 3; 4 5 6]
22
2×3 Matrix{Int64}:
23
 1  2  3
24
 4  5  6
25

26
julia> vec(a)
27
6-element Vector{Int64}:
28
 1
29
 4
30
 2
31
 5
32
 3
33
 6
34

35
julia> vec(1:3)
36
1:3
37
```
38

39
See also [`reshape`](@ref), [`dropdims`](@ref).
40
"""
41
vec(a::AbstractArray) = reshape(a,length(a))
10,931✔
42
vec(a::AbstractVector) = a
7,705✔
43

44
_sub(::Tuple{}, ::Tuple{}) = ()
×
45
_sub(t::Tuple, ::Tuple{}) = t
180✔
46
_sub(t::Tuple, s::Tuple) = _sub(tail(t), tail(s))
340✔
47

48
"""
49
    dropdims(A; dims)
50

51
Return an array with the same data as `A`, but with the dimensions specified by
52
`dims` removed. `size(A,d)` must equal 1 for every `d` in `dims`,
53
and repeated dimensions or numbers outside `1:ndims(A)` are forbidden.
54

55
The result shares the same underlying data as `A`, such that the
56
result is mutable if and only if `A` is mutable, and setting elements of one
57
alters the values of the other.
58

59
See also: [`reshape`](@ref), [`vec`](@ref).
60

61
# Examples
62
```jldoctest
63
julia> a = reshape(Vector(1:4),(2,2,1,1))
64
2×2×1×1 Array{Int64, 4}:
65
[:, :, 1, 1] =
66
 1  3
67
 2  4
68

69
julia> b = dropdims(a; dims=3)
70
2×2×1 Array{Int64, 3}:
71
[:, :, 1] =
72
 1  3
73
 2  4
74

75
julia> b[1,1,1] = 5; a
76
2×2×1×1 Array{Int64, 4}:
77
[:, :, 1, 1] =
78
 5  3
79
 2  4
80
```
81
"""
82
dropdims(A; dims) = _dropdims(A, dims)
465✔
83
function _dropdims(A::AbstractArray, dims::Dims)
175✔
84
    for i in eachindex(dims)
231✔
85
        1 <= dims[i] <= ndims(A) || throw(ArgumentError("dropped dims must be in range 1:ndims(A)"))
427✔
86
        length(axes(A, dims[i])) == 1 || throw(ArgumentError("dropped dims must all be size 1"))
418✔
87
        for j = 1:i-1
388✔
88
            dims[j] == dims[i] && throw(ArgumentError("dropped dims must be unique"))
280✔
89
        end
358✔
90
    end
554✔
91
    ox = axes(A)
186✔
92
    ax = _foldoneto((ds, d) -> d in dims ? ds : (ds..., axes(A,d)), (), Val(ndims(A)))
1,540✔
93
    if isconcretetype(eltype(ox))
186✔
94
        # if all the axes are the same type, we can use the tail as the
95
        # axes of the result rather than extracting one at each index
96
        return reshape(A, ax::typeof(_sub(ox, dims)))
180✔
97
    else
98
        return reshape(A, ax)
6✔
99
    end
100
end
101
_dropdims(A::AbstractArray, dim::Integer) = _dropdims(A, (Int(dim),))
87✔
102

103
"""
104
    insertdims(A; dims)
105

106
Inverse of [`dropdims`](@ref); return an array with new singleton dimensions
107
at every dimension in `dims`.
108

109
Repeated dimensions are forbidden and the largest entry in `dims` must be
110
less than or equal than `ndims(A) + length(dims)`.
111

112
The result shares the same underlying data as `A`, such that the
113
result is mutable if and only if `A` is mutable, and setting elements of one
114
alters the values of the other.
115

116
See also: [`dropdims`](@ref), [`reshape`](@ref), [`vec`](@ref).
117
# Examples
118
```jldoctest
119
julia> x = [1 2 3; 4 5 6]
120
2×3 Matrix{Int64}:
121
 1  2  3
122
 4  5  6
123

124
julia> insertdims(x, dims=3)
125
2×3×1 Array{Int64, 3}:
126
[:, :, 1] =
127
 1  2  3
128
 4  5  6
129

130
julia> insertdims(x, dims=(1,2,5)) == reshape(x, 1, 1, 2, 3, 1)
131
true
132

133
julia> dropdims(insertdims(x, dims=(1,2,5)), dims=(1,2,5))
134
2×3 Matrix{Int64}:
135
 1  2  3
136
 4  5  6
137
```
138

139
!!! compat "Julia 1.12"
140
    Requires Julia 1.12 or later.
141
"""
142
insertdims(A; dims) = _insertdims(A, dims)
321✔
143
function _insertdims(A::AbstractArray{T, N}, dims::NTuple{M, Int}) where {T, N, M}
129✔
144
    for i in eachindex(dims)
150✔
145
        1 ≤ dims[i] || throw(ArgumentError("the smallest entry in dims must be ≥ 1."))
345✔
146
        dims[i] ≤ N+M || throw(ArgumentError("the largest entry in dims must be not larger than the dimension of the array and the length of dims added"))
345✔
147
        for j = 1:i-1
333✔
148
            dims[j] == dims[i] && throw(ArgumentError("inserted dims must be unique"))
336✔
149
        end
462✔
150
    end
513✔
151

152
    # acc is a tuple, where the first entry is the final shape
153
    # the second entry off acc is a counter for the axes of A
154
    inds= Base._foldoneto((acc, i) ->
1,224✔
155
                            i ∈ dims
156
                                ? ((acc[1]..., Base.OneTo(1)), acc[2])
157
                                : ((acc[1]..., axes(A, acc[2])), acc[2] + 1),
158
                            ((), 1), Val(N+M))
159
    new_shape = inds[1]
126✔
160
    return reshape(A, new_shape)
126✔
161
end
162
_insertdims(A::AbstractArray, dim::Integer) = _insertdims(A, (Int(dim),))
42✔
163

164

165

166
## Unary operators ##
167

168
"""
169
    conj!(A)
170

171
Transform an array to its complex conjugate in-place.
172

173
See also [`conj`](@ref).
174

175
# Examples
176
```jldoctest
177
julia> A = [1+im 2-im; 2+2im 3+im]
178
2×2 Matrix{Complex{Int64}}:
179
 1+1im  2-1im
180
 2+2im  3+1im
181

182
julia> conj!(A);
183

184
julia> A
185
2×2 Matrix{Complex{Int64}}:
186
 1-1im  2+1im
187
 2-2im  3-1im
188
```
189
"""
190
conj!(A::AbstractArray{<:Number}) = (@inbounds broadcast!(conj, A, A); A)
361,116✔
191
conj!(x::AbstractArray{<:Real}) = x
9✔
192
conj!(A::AbstractArray) = (foreach(conj!, A); A)
6✔
193

194
"""
195
    conj(A::AbstractArray)
196

197
Return an array containing the complex conjugate of each entry in array `A`.
198

199
Equivalent to `conj.(A)`, except that when `eltype(A) <: Real`
200
`A` is returned without copying, and that when `A` has zero dimensions,
201
a 0-dimensional array is returned (rather than a scalar).
202

203
# Examples
204
```jldoctest
205
julia> conj([1, 2im, 3 + 4im])
206
3-element Vector{Complex{Int64}}:
207
 1 + 0im
208
 0 - 2im
209
 3 - 4im
210

211
julia> conj(fill(2 - im))
212
0-dimensional Array{Complex{Int64}, 0}:
213
2 + 1im
214
```
215
"""
216
conj(A::AbstractArray) = broadcast_preserving_zero_d(conj, A)
583✔
217
conj(A::AbstractArray{<:Real}) = A
499✔
218

219
"""
220
    real(A::AbstractArray)
221

222
Return an array containing the real part of each entry in array `A`.
223

224
Equivalent to `real.(A)`, except that when `eltype(A) <: Real`
225
`A` is returned without copying, and that when `A` has zero dimensions,
226
a 0-dimensional array is returned (rather than a scalar).
227

228
# Examples
229
```jldoctest
230
julia> real([1, 2im, 3 + 4im])
231
3-element Vector{Int64}:
232
 1
233
 0
234
 3
235

236
julia> real(fill(2 - im))
237
0-dimensional Array{Int64, 0}:
238
2
239
```
240
"""
241
real(A::AbstractArray) = broadcast_preserving_zero_d(real, A)
4,170✔
242
real(A::AbstractArray{<:Real}) = A
2,451✔
243

244
"""
245
    imag(A::AbstractArray)
246

247
Return an array containing the imaginary part of each entry in array `A`.
248

249
Equivalent to `imag.(A)`, except that when `A` has zero dimensions,
250
a 0-dimensional array is returned (rather than a scalar).
251

252
# Examples
253
```jldoctest
254
julia> imag([1, 2im, 3 + 4im])
255
3-element Vector{Int64}:
256
 0
257
 2
258
 4
259

260
julia> imag(fill(2 - im))
261
0-dimensional Array{Int64, 0}:
262
-1
263
```
264
"""
265
imag(A::AbstractArray) = broadcast_preserving_zero_d(imag, A)
2,592✔
266
imag(A::AbstractArray{<:Real}) = zero(A)
1,961✔
267

268
"""
269
    reim(A::AbstractArray)
270

271
Return a tuple of two arrays containing respectively the real and the imaginary
272
part of each entry in `A`.
273

274
Equivalent to `(real.(A), imag.(A))`, except that when `eltype(A) <: Real`
275
`A` is returned without copying to represent the real part, and that when `A` has
276
zero dimensions, a 0-dimensional array is returned (rather than a scalar).
277

278
# Examples
279
```jldoctest
280
julia> reim([1, 2im, 3 + 4im])
281
([1, 0, 3], [0, 2, 4])
282

283
julia> reim(fill(2 - im))
284
(fill(2), fill(-1))
285
```
286
"""
287
reim(A::AbstractArray)
288

289
-(A::AbstractArray) = broadcast_preserving_zero_d(-, A)
8,479✔
290

291
+(x::AbstractArray{<:Number}) = x
9✔
292
*(x::AbstractArray{<:Number,2}) = x
3✔
293

294
# index A[:,:,...,i,:,:,...] where "i" is in dimension "d"
295

296
"""
297
    selectdim(A, d::Integer, i)
298

299
Return a view of all the data of `A` where the index for dimension `d` equals `i`.
300

301
Equivalent to `view(A,:,:,...,i,:,:,...)` where `i` is in position `d`.
302

303
See also: [`eachslice`](@ref).
304

305
# Examples
306
```jldoctest
307
julia> A = [1 2 3 4; 5 6 7 8]
308
2×4 Matrix{Int64}:
309
 1  2  3  4
310
 5  6  7  8
311

312
julia> selectdim(A, 2, 3)
313
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
314
 3
315
 7
316

317
julia> selectdim(A, 2, 3:4)
318
2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
319
 3  4
320
 7  8
321
```
322
"""
323
@inline selectdim(A::AbstractArray, d::Integer, i) = _selectdim(A, d, i, _setindex(i, d, map(Slice, axes(A))...))
129✔
324
@noinline function _selectdim(A, d, i, idxs)
129✔
325
    d >= 1 || throw(ArgumentError("dimension must be ≥ 1, got $d"))
135✔
326
    nd = ndims(A)
123✔
327
    d > nd && (i == 1 || throw(BoundsError(A, (ntuple(Returns(Colon()),d-1)..., i))))
129✔
328
    return view(A, idxs...)
117✔
329
end
330

331
function circshift(a::AbstractArray, shiftamt::Real)
411✔
332
    circshift!(similar(a), a, (Integer(shiftamt),))
421✔
333
end
334
circshift(a::AbstractArray, shiftamt::DimsInteger) = circshift!(similar(a), a, shiftamt)
108✔
335
"""
336
    circshift(A, shifts)
337

338
Circularly shift, i.e. rotate, the data in `A`. The second argument is a tuple or
339
vector giving the amount to shift in each dimension, or an integer to shift only in the
340
first dimension.
341

342
The generated code is most efficient when the shift amounts are known at compile-time, i.e.,
343
compile-time constants.
344

345
See also: [`circshift!`](@ref), [`circcopy!`](@ref), [`bitrotate`](@ref), [`<<`](@ref).
346

347
# Examples
348
```jldoctest
349
julia> b = reshape(Vector(1:16), (4,4))
350
4×4 Matrix{Int64}:
351
 1  5   9  13
352
 2  6  10  14
353
 3  7  11  15
354
 4  8  12  16
355

356
julia> circshift(b, (0,2))
357
4×4 Matrix{Int64}:
358
  9  13  1  5
359
 10  14  2  6
360
 11  15  3  7
361
 12  16  4  8
362

363
julia> circshift(b, (-1,0))
364
4×4 Matrix{Int64}:
365
 2  6  10  14
366
 3  7  11  15
367
 4  8  12  16
368
 1  5   9  13
369

370
julia> a = BitArray([true, true, false, false, true])
371
5-element BitVector:
372
 1
373
 1
374
 0
375
 0
376
 1
377

378
julia> circshift(a, 1)
379
5-element BitVector:
380
 1
381
 1
382
 1
383
 0
384
 0
385

386
julia> circshift(a, -1)
387
5-element BitVector:
388
 1
389
 0
390
 0
391
 1
392
 1
393

394
julia> x = (1, 2, 3, 4, 5)
395
(1, 2, 3, 4, 5)
396

397
julia> circshift(x, 4)
398
(2, 3, 4, 5, 1)
399

400
julia> z = (1, 'a', -7.0, 3)
401
(1, 'a', -7.0, 3)
402

403
julia> circshift(z, -1)
404
('a', -7.0, 3, 1)
405
```
406
"""
407
function circshift(a::AbstractArray, shiftamt)
3✔
408
    circshift!(similar(a), a, map(Integer, (shiftamt...,)))
3✔
409
end
410

411
## Other array functions ##
412

413
"""
414
    repeat(A::AbstractArray, counts::Integer...)
415

416
Construct an array by repeating array `A` a given number of times in each dimension, specified by `counts`.
417

418
See also: [`fill`](@ref), [`Iterators.repeated`](@ref), [`Iterators.cycle`](@ref).
419

420
# Examples
421
```jldoctest
422
julia> repeat([1, 2, 3], 2)
423
6-element Vector{Int64}:
424
 1
425
 2
426
 3
427
 1
428
 2
429
 3
430

431
julia> repeat([1, 2, 3], 2, 3)
432
6×3 Matrix{Int64}:
433
 1  1  1
434
 2  2  2
435
 3  3  3
436
 1  1  1
437
 2  2  2
438
 3  3  3
439
```
440
"""
441
function repeat(A::AbstractArray, counts...)
350✔
442
    return repeat(A, outer=counts)
790✔
443
end
444

445
"""
446
    repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))
447

448
Construct an array by repeating the entries of `A`. The i-th element of `inner` specifies
449
the number of times that the individual entries of the i-th dimension of `A` should be
450
repeated. The i-th element of `outer` specifies the number of times that a slice along the
451
i-th dimension of `A` should be repeated. If `inner` or `outer` are omitted, no repetition
452
is performed.
453

454
# Examples
455
```jldoctest
456
julia> repeat(1:2, inner=2)
457
4-element Vector{Int64}:
458
 1
459
 1
460
 2
461
 2
462

463
julia> repeat(1:2, outer=2)
464
4-element Vector{Int64}:
465
 1
466
 2
467
 1
468
 2
469

470
julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
471
4×6 Matrix{Int64}:
472
 1  2  1  2  1  2
473
 1  2  1  2  1  2
474
 3  4  3  4  3  4
475
 3  4  3  4  3  4
476
```
477
"""
478
function repeat(A::AbstractArray; inner = nothing, outer = nothing)
1,018✔
479
    return _RepeatInnerOuter.repeat(A, inner=inner, outer=outer)
1,042✔
480
end
481

482
module _RepeatInnerOuter
483

484
function repeat(arr; inner=nothing, outer=nothing)
1,862✔
485
    check(arr, inner, outer)
1,984✔
486
    arr, inner, outer = resolve(arr, inner, outer)
970✔
487
    repeat_inner_outer(arr, inner, outer)
970✔
488
end
489

490
to_tuple(t::Tuple) = t
829✔
491
to_tuple(x::Integer) = (x,)
39✔
492
to_tuple(itr) = tuple(itr...)
27✔
493

494
function pad(a, b)
18✔
495
    N = max(length(a), length(b))
853✔
496
    Base.fill_to_length(a, 1, Val(N)), Base.fill_to_length(b, 1, Val(N))
853✔
497
end
498
function pad(a, b, c)
9✔
499
    N = max(max(length(a), length(b)), length(c))
39✔
500
    Base.fill_to_length(a, 1, Val(N)), Base.fill_to_length(b, 1, Val(N)), Base.fill_to_length(c, 1, Val(N))
39✔
501
end
502

503
function resolve(arr::AbstractArray{<:Any, N}, inner::NTuple{N, Any}, outer::NTuple{N,Any}) where {N}
504
    arr, inner, outer
72✔
505
end
506
function resolve(arr, inner, outer)
9✔
507
    dims, inner, outer = pad(size(arr), to_tuple(inner), to_tuple(outer))
39✔
508
    reshape(arr, dims), inner, outer
39✔
509
end
510
function resolve(arr, inner::Nothing, outer::Nothing)
511
    return arr, inner, outer
6✔
512
end
513
function resolve(arr, inner::Nothing, outer)
12✔
514
    dims, outer = pad(size(arr), to_tuple(outer))
820✔
515
    reshape(arr, dims), inner, outer
820✔
516
end
517
function resolve(arr, inner, outer::Nothing)
6✔
518
    dims, inner = pad(size(arr), to_tuple(inner))
33✔
519
    reshape(arr, dims), inner, outer
33✔
520
end
521

522
function check(arr, inner, outer)
126✔
523
    if inner !== nothing
988✔
524
        # TODO: Currently one based indexing is demanded for inner !== nothing,
525
        # but not for outer !== nothing. Decide for something consistent.
526
        Base.require_one_based_indexing(arr)
165✔
527
        if !all(n -> n isa Integer, inner)
525✔
UNCOV
528
            throw(ArgumentError("repeat requires integer counts, got inner = $inner"))
×
529
        end
530
        if any(<(0), inner)
423✔
531
            throw(ArgumentError("no inner repetition count may be negative; got $inner"))
3✔
532
        end
533
        if length(inner) < ndims(arr)
156✔
534
            throw(ArgumentError("number of inner repetitions ($(length(inner))) cannot be less than number of dimensions of input array ($(ndims(arr)))"))
6✔
535
        end
536
    end
537
    if outer !== nothing
976✔
538
        if !all(n -> n isa Integer, outer)
2,319✔
UNCOV
539
            throw(ArgumentError("repeat requires integer counts, got outer = $outer"))
×
540
        end
541
        if any(<(0), outer)
2,110✔
UNCOV
542
            throw(ArgumentError("no outer repetition count may be negative; got $outer"))
×
543
        end
544
        if (length(outer) < ndims(arr)) && (inner !== nothing)
937✔
545
            throw(ArgumentError("number of outer repetitions ($(length(outer))) cannot be less than number of dimensions of input array ($(ndims(arr)))"))
6✔
546
        end
547
    end
548
end
549

550
repeat_inner_outer(arr, inner::Nothing, outer::Nothing) = arr
6✔
551
repeat_inner_outer(arr, ::Nothing, outer) = repeat_outer(arr, outer)
820✔
552
repeat_inner_outer(arr, inner, ::Nothing) = repeat_inner(arr, inner)
33✔
553
repeat_inner_outer(arr, inner, outer) = repeat_outer(repeat_inner(arr, inner), outer)
111✔
554

555
function repeat_outer(a::AbstractMatrix, (m,n)::NTuple{2, Any})
203✔
556
    o, p = size(a,1), size(a,2)
203✔
557
    b = similar(a, o*m, p*n)
203✔
558
    for j=1:n
203✔
559
        d = (j-1)*p+1
381✔
560
        R = d:d+p-1
387✔
561
        for i=1:m
381✔
562
            c = (i-1)*o+1
546✔
563
            @inbounds b[c:c+o-1, R] = a
552✔
564
        end
747✔
565
    end
582✔
566
    return b
203✔
567
end
568

569
function repeat_outer(a::AbstractVector, (m,)::Tuple{Any})
23✔
570
    o = length(a)
704✔
571
    b = similar(a, o*m)
704✔
572
    for i=1:m
704✔
573
        c = (i-1)*o+1
3,029,670✔
574
        @inbounds b[c:c+o-1] = a
6,082,524✔
575
    end
6,058,745✔
576
    return b
704✔
577
end
578

579
function repeat_outer(arr::AbstractArray{<:Any,N}, dims::NTuple{N,Any}) where {N}
24✔
580
    insize  = size(arr)
24✔
581
    outsize = map(*, insize, dims)
24✔
582
    out = similar(arr, outsize)
24✔
583
    for I in CartesianIndices(arr)
48✔
584
        for J in CartesianIndices(dims)
588✔
585
            TIJ = map(Tuple(I), Tuple(J), insize) do i, j, d
1,908✔
586
                i + d * (j-1)
5,724✔
587
            end
588
            IJ = CartesianIndex(TIJ)
1,908✔
589
            @inbounds out[IJ] = arr[I]
1,908✔
590
        end
2,202✔
591
    end
318✔
592
    return out
24✔
593
end
594

595
function repeat_inner(arr, inner)
144✔
596
    outsize = map(*, size(arr), inner)
144✔
597
    out = similar(arr, outsize)
144✔
598
    for I in CartesianIndices(arr)
234✔
599
        for J in CartesianIndices(inner)
759✔
600
            TIJ = map(Tuple(I), Tuple(J), inner) do i, j, d
948✔
601
                (i-1) * d + j
1,980✔
602
            end
603
            IJ = CartesianIndex(TIJ)
948✔
604
            @inbounds out[IJ] = arr[I]
948✔
605
        end
1,359✔
606
    end
576✔
607
    return out
144✔
608
end
609

610
end#module
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc