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

JuliaLang / julia / #37798

05 Jun 2024 07:57AM UTC coverage: 83.152% (-3.8%) from 86.908%
#37798

push

local

web-flow
Use the public `wait()` in the `errormonitor()` docstring (#54650)

72847 of 87607 relevant lines covered (83.15%)

14515294.14 hits per line

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

53.44
/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)
3,358✔
6
iszero(x::AbstractArray) = all(iszero,x)
3,882✔
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))
3,327✔
42
vec(a::AbstractVector) = a
546✔
43

44
_sub(::Tuple{}, ::Tuple{}) = ()
×
45
_sub(t::Tuple, ::Tuple{}) = t
26✔
46
_sub(t::Tuple, s::Tuple) = _sub(tail(t), tail(s))
36✔
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)
68✔
83
function _dropdims(A::AbstractArray, dims::Dims)
20✔
84
    for i in eachindex(dims)
34✔
85
        1 <= dims[i] <= ndims(A) || throw(ArgumentError("dropped dims must be in range 1:ndims(A)"))
50✔
86
        length(axes(A, dims[i])) == 1 || throw(ArgumentError("dropped dims must all be size 1"))
49✔
87
        for j = 1:i-1
43✔
88
            dims[j] == dims[i] && throw(ArgumentError("dropped dims must be unique"))
16✔
89
        end
15✔
90
    end
54✔
91
    ax = _foldoneto((ds, d) -> d in dims ? ds : (ds..., axes(A,d)), (), Val(ndims(A)))
150✔
92
    reshape(A, ax::typeof(_sub(axes(A), dims)))
26✔
93
end
94
_dropdims(A::AbstractArray, dim::Integer) = _dropdims(A, (Int(dim),))
16✔
95

96
## Unary operators ##
97

98
"""
99
    conj!(A)
100

101
Transform an array to its complex conjugate in-place.
102

103
See also [`conj`](@ref).
104

105
# Examples
106
```jldoctest
107
julia> A = [1+im 2-im; 2+2im 3+im]
108
2×2 Matrix{Complex{Int64}}:
109
 1+1im  2-1im
110
 2+2im  3+1im
111

112
julia> conj!(A);
113

114
julia> A
115
2×2 Matrix{Complex{Int64}}:
116
 1-1im  2+1im
117
 2-2im  3-1im
118
```
119
"""
120
conj!(A::AbstractArray{<:Number}) = (@inbounds broadcast!(conj, A, A); A)
120,115✔
121
conj!(x::AbstractArray{<:Real}) = x
2✔
122
conj!(A::AbstractArray) = (foreach(conj!, A); A)
×
123

124
"""
125
    conj(A::AbstractArray)
126

127
Return an array containing the complex conjugate of each entry in array `A`.
128

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

133
# Examples
134
```jldoctest
135
julia> conj([1, 2im, 3 + 4im])
136
3-element Vector{Complex{Int64}}:
137
 1 + 0im
138
 0 - 2im
139
 3 - 4im
140

141
julia> conj(fill(2 - im))
142
0-dimensional Array{Complex{Int64}, 0}:
143
2 + 1im
144
```
145
"""
146
conj(A::AbstractArray) = broadcast_preserving_zero_d(conj, A)
160✔
147
conj(A::AbstractArray{<:Real}) = A
164✔
148

149
"""
150
    real(A::AbstractArray)
151

152
Return an array containing the real part of each entry in array `A`.
153

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

158
# Examples
159
```jldoctest
160
julia> real([1, 2im, 3 + 4im])
161
3-element Vector{Int64}:
162
 1
163
 0
164
 3
165

166
julia> real(fill(2 - im))
167
0-dimensional Array{Int64, 0}:
168
2
169
```
170
"""
171
real(A::AbstractArray) = broadcast_preserving_zero_d(real, A)
1,327✔
172
real(A::AbstractArray{<:Real}) = A
559✔
173

174
"""
175
    imag(A::AbstractArray)
176

177
Return an array containing the imaginary part of each entry in array `A`.
178

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

182
# Examples
183
```jldoctest
184
julia> imag([1, 2im, 3 + 4im])
185
3-element Vector{Int64}:
186
 0
187
 2
188
 4
189

190
julia> imag(fill(2 - im))
191
0-dimensional Array{Int64, 0}:
192
-1
193
```
194
"""
195
imag(A::AbstractArray) = broadcast_preserving_zero_d(imag, A)
853✔
196
imag(A::AbstractArray{<:Real}) = zero(A)
302✔
197

198
"""
199
    reim(A::AbstractArray)
200

201
Return a tuple of two arrays containing respectively the real and the imaginary
202
part of each entry in `A`.
203

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

208
# Examples
209
```jldoctest
210
julia> reim([1, 2im, 3 + 4im])
211
([1, 0, 3], [0, 2, 4])
212

213
julia> reim(fill(2 - im))
214
(fill(2), fill(-1))
215
```
216
"""
217
reim(A::AbstractArray)
218

219
-(A::AbstractArray) = broadcast_preserving_zero_d(-, A)
2,334✔
220

221
+(x::AbstractArray{<:Number}) = x
3✔
222
*(x::AbstractArray{<:Number,2}) = x
1✔
223

224
# index A[:,:,...,i,:,:,...] where "i" is in dimension "d"
225

226
"""
227
    selectdim(A, d::Integer, i)
228

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

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

233
See also: [`eachslice`](@ref).
234

235
# Examples
236
```jldoctest
237
julia> A = [1 2 3 4; 5 6 7 8]
238
2×4 Matrix{Int64}:
239
 1  2  3  4
240
 5  6  7  8
241

242
julia> selectdim(A, 2, 3)
243
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
244
 3
245
 7
246

247
julia> selectdim(A, 2, 3:4)
248
2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
249
 3  4
250
 7  8
251
```
252
"""
253
@inline selectdim(A::AbstractArray, d::Integer, i) = _selectdim(A, d, i, _setindex(i, d, map(Slice, axes(A))...))
×
254
@noinline function _selectdim(A, d, i, idxs)
×
255
    d >= 1 || throw(ArgumentError("dimension must be ≥ 1, got $d"))
×
256
    nd = ndims(A)
×
257
    d > nd && (i == 1 || throw(BoundsError(A, (ntuple(Returns(Colon()),d-1)..., i))))
×
258
    return view(A, idxs...)
×
259
end
260

261
function circshift(a::AbstractArray, shiftamt::Real)
6✔
262
    circshift!(similar(a), a, (Integer(shiftamt),))
23✔
263
end
264
circshift(a::AbstractArray, shiftamt::DimsInteger) = circshift!(similar(a), a, shiftamt)
3✔
265
"""
266
    circshift(A, shifts)
267

268
Circularly shift, i.e. rotate, the data in `A`. The second argument is a tuple or
269
vector giving the amount to shift in each dimension, or an integer to shift only in the
270
first dimension.
271

272
The generated code is most efficient when the shift amounts are known at compile-time, i.e.,
273
compile-time constants.
274

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

277
# Examples
278
```jldoctest
279
julia> b = reshape(Vector(1:16), (4,4))
280
4×4 Matrix{Int64}:
281
 1  5   9  13
282
 2  6  10  14
283
 3  7  11  15
284
 4  8  12  16
285

286
julia> circshift(b, (0,2))
287
4×4 Matrix{Int64}:
288
  9  13  1  5
289
 10  14  2  6
290
 11  15  3  7
291
 12  16  4  8
292

293
julia> circshift(b, (-1,0))
294
4×4 Matrix{Int64}:
295
 2  6  10  14
296
 3  7  11  15
297
 4  8  12  16
298
 1  5   9  13
299

300
julia> a = BitArray([true, true, false, false, true])
301
5-element BitVector:
302
 1
303
 1
304
 0
305
 0
306
 1
307

308
julia> circshift(a, 1)
309
5-element BitVector:
310
 1
311
 1
312
 1
313
 0
314
 0
315

316
julia> circshift(a, -1)
317
5-element BitVector:
318
 1
319
 0
320
 0
321
 1
322
 1
323

324
julia> x = (1, 2, 3, 4, 5)
325
(1, 2, 3, 4, 5)
326

327
julia> circshift(x, 4)
328
(2, 3, 4, 5, 1)
329

330
julia> z = (1, 'a', -7.0, 3)
331
(1, 'a', -7.0, 3)
332

333
julia> circshift(z, -1)
334
('a', -7.0, 3, 1)
335
```
336
"""
337
function circshift(a::AbstractArray, shiftamt)
×
338
    circshift!(similar(a), a, map(Integer, (shiftamt...,)))
×
339
end
340

341
## Other array functions ##
342

343
"""
344
    repeat(A::AbstractArray, counts::Integer...)
345

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

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

350
# Examples
351
```jldoctest
352
julia> repeat([1, 2, 3], 2)
353
6-element Vector{Int64}:
354
 1
355
 2
356
 3
357
 1
358
 2
359
 3
360

361
julia> repeat([1, 2, 3], 2, 3)
362
6×3 Matrix{Int64}:
363
 1  1  1
364
 2  2  2
365
 3  3  3
366
 1  1  1
367
 2  2  2
368
 3  3  3
369
```
370
"""
371
function repeat(A::AbstractArray, counts...)
80✔
372
    return repeat(A, outer=counts)
283✔
373
end
374

375
"""
376
    repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))
377

378
Construct an array by repeating the entries of `A`. The i-th element of `inner` specifies
379
the number of times that the individual entries of the i-th dimension of `A` should be
380
repeated. The i-th element of `outer` specifies the number of times that a slice along the
381
i-th dimension of `A` should be repeated. If `inner` or `outer` are omitted, no repetition
382
is performed.
383

384
# Examples
385
```jldoctest
386
julia> repeat(1:2, inner=2)
387
4-element Vector{Int64}:
388
 1
389
 1
390
 2
391
 2
392

393
julia> repeat(1:2, outer=2)
394
4-element Vector{Int64}:
395
 1
396
 2
397
 1
398
 2
399

400
julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
401
4×6 Matrix{Int64}:
402
 1  2  1  2  1  2
403
 1  2  1  2  1  2
404
 3  4  3  4  3  4
405
 3  4  3  4  3  4
406
```
407
"""
408
function repeat(A::AbstractArray; inner = nothing, outer = nothing)
290✔
409
    return _RepeatInnerOuter.repeat(A, inner=inner, outer=outer)
290✔
410
end
411

412
module _RepeatInnerOuter
413

414
function repeat(arr; inner=nothing, outer=nothing)
324✔
415
    check(arr, inner, outer)
574✔
416
    arr, inner, outer = resolve(arr, inner, outer)
278✔
417
    repeat_inner_outer(arr, inner, outer)
278✔
418
end
419

420
to_tuple(t::Tuple) = t
278✔
421
to_tuple(x::Integer) = (x,)
×
422
to_tuple(itr) = tuple(itr...)
×
423

424
function pad(a, b)
425
    N = max(length(a), length(b))
278✔
426
    Base.fill_to_length(a, 1, Val(N)), Base.fill_to_length(b, 1, Val(N))
278✔
427
end
428
function pad(a, b, c)
×
429
    N = max(max(length(a), length(b)), length(c))
×
430
    Base.fill_to_length(a, 1, Val(N)), Base.fill_to_length(b, 1, Val(N)), Base.fill_to_length(c, 1, Val(N))
×
431
end
432

433
function resolve(arr::AbstractArray{<:Any, N}, inner::NTuple{N, Any}, outer::NTuple{N,Any}) where {N}
×
434
    arr, inner, outer
×
435
end
436
function resolve(arr, inner, outer)
×
437
    dims, inner, outer = pad(size(arr), to_tuple(inner), to_tuple(outer))
×
438
    reshape(arr, dims), inner, outer
×
439
end
440
function resolve(arr, inner::Nothing, outer::Nothing)
×
441
    return arr, inner, outer
×
442
end
443
function resolve(arr, inner::Nothing, outer)
444
    dims, outer = pad(size(arr), to_tuple(outer))
278✔
445
    reshape(arr, dims), inner, outer
278✔
446
end
447
function resolve(arr, inner, outer::Nothing)
×
448
    dims, inner = pad(size(arr), to_tuple(inner))
×
449
    reshape(arr, dims), inner, outer
×
450
end
451

452
function check(arr, inner, outer)
453
    if inner !== nothing
278✔
454
        # TODO: Currently one based indexing is demanded for inner !== nothing,
455
        # but not for outer !== nothing. Decide for something consistent.
456
        Base.require_one_based_indexing(arr)
×
457
        if any(<(0), inner)
×
458
            throw(ArgumentError("no inner repetition count may be negative; got $inner"))
×
459
        end
460
        if length(inner) < ndims(arr)
×
461
            throw(ArgumentError("number of inner repetitions ($(length(inner))) cannot be less than number of dimensions of input array ($(ndims(arr)))"))
×
462
        end
463
    end
464
    if outer !== nothing
278✔
465
        if any(<(0), outer)
574✔
466
            throw(ArgumentError("no outer repetition count may be negative; got $outer"))
×
467
        end
468
        if (length(outer) < ndims(arr)) && (inner !== nothing)
278✔
469
            throw(ArgumentError("number of outer repetitions ($(length(outer))) cannot be less than number of dimensions of input array ($(ndims(arr)))"))
×
470
        end
471
    end
472
end
473

474
repeat_inner_outer(arr, inner::Nothing, outer::Nothing) = arr
×
475
repeat_inner_outer(arr, ::Nothing, outer) = repeat_outer(arr, outer)
278✔
476
repeat_inner_outer(arr, inner, ::Nothing) = repeat_inner(arr, inner)
×
477
repeat_inner_outer(arr, inner, outer) = repeat_outer(repeat_inner(arr, inner), outer)
×
478

479
function repeat_outer(a::AbstractMatrix, (m,n)::NTuple{2, Any})
37✔
480
    o, p = size(a,1), size(a,2)
37✔
481
    b = similar(a, o*m, p*n)
59✔
482
    for j=1:n
37✔
483
        d = (j-1)*p+1
69✔
484
        R = d:d+p-1
69✔
485
        for i=1:m
69✔
486
            c = (i-1)*o+1
95✔
487
            @inbounds b[c:c+o-1, R] = a
95✔
488
        end
134✔
489
    end
109✔
490
    return b
37✔
491
end
492

493
function repeat_outer(a::AbstractVector, (m,)::Tuple{Any})
241✔
494
    o = length(a)
241✔
495
    b = similar(a, o*m)
417✔
496
    for i=1:m
241✔
497
        c = (i-1)*o+1
1,011,094✔
498
        @inbounds b[c:c+o-1] = a
2,019,846✔
499
    end
2,021,988✔
500
    return b
241✔
501
end
502

503
function repeat_outer(arr::AbstractArray{<:Any,N}, dims::NTuple{N,Any}) where {N}
×
504
    insize  = size(arr)
×
505
    outsize = map(*, insize, dims)
×
506
    out = similar(arr, outsize)
×
507
    for I in CartesianIndices(arr)
×
508
        for J in CartesianIndices(dims)
×
509
            TIJ = map(Tuple(I), Tuple(J), insize) do i, j, d
×
510
                i + d * (j-1)
×
511
            end
512
            IJ = CartesianIndex(TIJ)
×
513
            @inbounds out[IJ] = arr[I]
×
514
        end
×
515
    end
×
516
    return out
×
517
end
518

519
function repeat_inner(arr, inner)
×
520
    outsize = map(*, size(arr), inner)
×
521
    out = similar(arr, outsize)
×
522
    for I in CartesianIndices(arr)
×
523
        for J in CartesianIndices(inner)
×
524
            TIJ = map(Tuple(I), Tuple(J), inner) do i, j, d
×
525
                (i-1) * d + j
×
526
            end
527
            IJ = CartesianIndex(TIJ)
×
528
            @inbounds out[IJ] = arr[I]
×
529
        end
×
530
    end
×
531
    return out
×
532
end
533

534
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