-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
generic.jl
1519 lines (1264 loc) · 34.7 KB
/
generic.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
## linalg.jl: Some generic Linear Algebra definitions
function generic_mul!(C::AbstractArray, X::AbstractArray, s::Number)
if length(C) != length(X)
throw(DimensionMismatch("first array has length $(length(C)) which does not match the length of the second, $(length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds C[IC] = X[IX]*s
end
C
end
function generic_mul!(C::AbstractArray, s::Number, X::AbstractArray)
if length(C) != length(X)
throw(DimensionMismatch("first array has length $(length(C)) which does not
match the length of the second, $(length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds C[IC] = s*X[IX]
end
C
end
mul!(C::AbstractArray, s::Number, X::AbstractArray) = generic_mul!(C, X, s)
mul!(C::AbstractArray, X::AbstractArray, s::Number) = generic_mul!(C, s, X)
# For better performance when input and output are the same array
# See https://github.com/JuliaLang/julia/issues/8415#issuecomment-56608729
"""
rmul!(A::AbstractArray, b::Number)
Scale an array `A` by a scalar `b` overwriting `A` in-place. Use
[`lmul!`](@ref) to multiply scalar from left. The scaling operation
respects the semantics of the multiplication [`*`](@ref) between an
element of `A` and `b`. In particular, this also applies to
multiplication involving non-finite numbers such as `NaN` and `±Inf`.
!!! compat "Julia 1.1"
Prior to Julia 1.1, `NaN` and `±Inf` entries in `A` were treated
inconsistently.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rmul!(A, 2)
2×2 Array{Int64,2}:
2 4
6 8
julia> rmul!([NaN], 0.0)
1-element Array{Float64,1}:
NaN
```
"""
function rmul!(X::AbstractArray, s::Number)
@simd for I in eachindex(X)
@inbounds X[I] *= s
end
X
end
"""
lmul!(a::Number, B::AbstractArray)
Scale an array `B` by a scalar `a` overwriting `B` in-place. Use
[`rmul!`](@ref) to multiply scalar from right. The scaling operation
respects the semantics of the multiplication [`*`](@ref) between `a`
and an element of `B`. In particular, this also applies to
multiplication involving non-finite numbers such as `NaN` and `±Inf`.
!!! compat "Julia 1.1"
Prior to Julia 1.1, `NaN` and `±Inf` entries in `B` were treated
inconsistently.
# Examples
```jldoctest
julia> B = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> lmul!(2, B)
2×2 Array{Int64,2}:
2 4
6 8
julia> lmul!(0.0, [Inf])
1-element Array{Float64,1}:
NaN
```
"""
function lmul!(s::Number, X::AbstractArray)
@simd for I in eachindex(X)
@inbounds X[I] = s*X[I]
end
X
end
"""
rdiv!(A::AbstractArray, b::Number)
Divide each entry in an array `A` by a scalar `b` overwriting `A`
in-place. Use [`ldiv!`](@ref) to divide scalar from left.
# Examples
```jldoctest
julia> A = [1.0 2.0; 3.0 4.0]
2×2 Array{Float64,2}:
1.0 2.0
3.0 4.0
julia> rdiv!(A, 2.0)
2×2 Array{Float64,2}:
0.5 1.0
1.5 2.0
```
"""
function rdiv!(X::AbstractArray, s::Number)
@simd for I in eachindex(X)
@inbounds X[I] /= s
end
X
end
"""
ldiv!(a::Number, B::AbstractArray)
Divide each entry in an array `B` by a scalar `a` overwriting `B`
in-place. Use [`rdiv!`](@ref) to divide scalar from right.
# Examples
```jldoctest
julia> B = [1.0 2.0; 3.0 4.0]
2×2 Array{Float64,2}:
1.0 2.0
3.0 4.0
julia> ldiv!(2.0, B)
2×2 Array{Float64,2}:
0.5 1.0
1.5 2.0
```
"""
function ldiv!(s::Number, X::AbstractArray)
@simd for I in eachindex(X)
@inbounds X[I] = s\X[I]
end
X
end
"""
cross(x, y)
×(x,y)
Compute the cross product of two 3-vectors.
# Examples
```jldoctest
julia> a = [0;1;0]
3-element Array{Int64,1}:
0
1
0
julia> b = [0;0;1]
3-element Array{Int64,1}:
0
0
1
julia> cross(a,b)
3-element Array{Int64,1}:
1
0
0
```
"""
function cross(a::AbstractVector, b::AbstractVector)
if !(length(a) == length(b) == 3)
throw(DimensionMismatch("cross product is only defined for vectors of length 3"))
end
a1, a2, a3 = a
b1, b2, b3 = b
[a2*b3-a3*b2, a3*b1-a1*b3, a1*b2-a2*b1]
end
"""
triu(M)
Upper triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
0.0 1.0 1.0 1.0
0.0 0.0 1.0 1.0
0.0 0.0 0.0 1.0
```
"""
triu(M::AbstractMatrix) = triu!(copy(M))
"""
tril(M)
Lower triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a)
4×4 Array{Float64,2}:
1.0 0.0 0.0 0.0
1.0 1.0 0.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
```
"""
tril(M::AbstractMatrix) = tril!(copy(M))
"""
triu(M, k::Integer)
Returns the upper triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a,3)
4×4 Array{Float64,2}:
0.0 0.0 0.0 1.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
julia> triu(a,-3)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
```
"""
triu(M::AbstractMatrix,k::Integer) = triu!(copy(M),k)
"""
tril(M, k::Integer)
Returns the lower triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,3)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,-3)
4×4 Array{Float64,2}:
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0
```
"""
tril(M::AbstractMatrix,k::Integer) = tril!(copy(M),k)
"""
triu!(M)
Upper triangle of a matrix, overwriting `M` in the process.
See also [`triu`](@ref).
"""
triu!(M::AbstractMatrix) = triu!(M,0)
"""
tril!(M)
Lower triangle of a matrix, overwriting `M` in the process.
See also [`tril`](@ref).
"""
tril!(M::AbstractMatrix) = tril!(M,0)
diag(A::AbstractVector) = throw(ArgumentError("use diagm instead of diag to construct a diagonal matrix"))
###########################################################################################
# Dot products and norms
# special cases of norm; note that they don't need to handle isempty(x)
function generic_normMinusInf(x)
(v, s) = iterate(x)::Tuple
minabs = norm(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
vnorm = norm(v)
minabs = ifelse(isnan(minabs) | (minabs < vnorm), minabs, vnorm)
end
return float(minabs)
end
function generic_normInf(x)
(v, s) = iterate(x)::Tuple
maxabs = norm(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
vnorm = norm(v)
maxabs = ifelse(isnan(maxabs) | (maxabs > vnorm), maxabs, vnorm)
end
return float(maxabs)
end
function generic_norm1(x)
(v, s) = iterate(x)::Tuple
av = float(norm(v))
T = typeof(av)
sum::promote_type(Float64, T) = av
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm(v)
end
return convert(T, sum)
end
# faster computation of norm(x)^2, avoiding overflow for integers
norm_sqr(x) = norm(x)^2
norm_sqr(x::Number) = abs2(x)
norm_sqr(x::Union{T,Complex{T},Rational{T}}) where {T<:Integer} = abs2(float(x))
function generic_norm2(x)
maxabs = normInf(x)
(maxabs == 0 || isinf(maxabs)) && return maxabs
(v, s) = iterate(x)::Tuple
T = typeof(maxabs)
if isfinite(length(x)*maxabs*maxabs) && maxabs*maxabs != 0 # Scaling not necessary
sum::promote_type(Float64, T) = norm_sqr(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm_sqr(v)
end
return convert(T, sqrt(sum))
else
sum = abs2(norm(v)/maxabs)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += (norm(v)/maxabs)^2
end
return convert(T, maxabs*sqrt(sum))
end
end
# Compute L_p norm ‖x‖ₚ = sum(abs(x).^p)^(1/p)
# (Not technically a "norm" for p < 1.)
function generic_normp(x, p)
(v, s) = iterate(x)::Tuple
if p > 1 || p < -1 # might need to rescale to avoid overflow
maxabs = p > 1 ? normInf(x) : normMinusInf(x)
(maxabs == 0 || isinf(maxabs)) && return maxabs
T = typeof(maxabs)
else
T = typeof(float(norm(v)))
end
spp::promote_type(Float64, T) = p
if -1 <= p <= 1 || (isfinite(length(x)*maxabs^spp) && maxabs^spp != 0) # scaling not necessary
sum::promote_type(Float64, T) = norm(v)^spp
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm(v)^spp
end
return convert(T, sum^inv(spp))
else # rescaling
sum = (norm(v)/maxabs)^spp
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += (norm(v)/maxabs)^spp
end
return convert(T, maxabs*sum^inv(spp))
end
end
normMinusInf(x) = generic_normMinusInf(x)
normInf(x) = generic_normInf(x)
norm1(x) = generic_norm1(x)
norm2(x) = generic_norm2(x)
normp(x, p) = generic_normp(x, p)
"""
norm(A, p::Real=2)
For any iterable container `A` (including arrays of any dimension) of numbers (or any
element type for which `norm` is defined), compute the `p`-norm (defaulting to `p=2`) as if
`A` were a vector of the corresponding length.
The `p`-norm is defined as
```math
\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p}
```
with ``a_i`` the entries of ``A``, ``| a_i |`` the [`norm`](@ref) of ``a_i``, and
``n`` the length of ``A``. Since the `p`-norm is computed using the [`norm`](@ref)s
of the entries of `A`, the `p`-norm of a vector of vectors is not compatible with
the interpretation of it as a block vector in general if `p != 2`.
`p` can assume any numeric value (even though not all values produce a
mathematically valid vector norm). In particular, `norm(A, Inf)` returns the largest value
in `abs.(A)`, whereas `norm(A, -Inf)` returns the smallest. If `A` is a matrix and `p=2`,
then this is equivalent to the Frobenius norm.
The second argument `p` is not necessarily a part of the interface for `norm`, i.e. a custom
type may only implement `norm(A)` without second argument.
Use [`opnorm`](@ref) to compute the operator norm of a matrix.
# Examples
```jldoctest
julia> v = [3, -2, 6]
3-element Array{Int64,1}:
3
-2
6
julia> norm(v)
7.0
julia> norm(v, 1)
11.0
julia> norm(v, Inf)
6.0
julia> norm([1 2 3; 4 5 6; 7 8 9])
16.881943016134134
julia> norm([1 2 3 4 5 6 7 8 9])
16.881943016134134
julia> norm(1:9)
16.881943016134134
julia> norm(hcat(v,v), 1) == norm(vcat(v,v), 1) != norm([v,v], 1)
true
julia> norm(hcat(v,v), 2) == norm(vcat(v,v), 2) == norm([v,v], 2)
true
julia> norm(hcat(v,v), Inf) == norm(vcat(v,v), Inf) != norm([v,v], Inf)
true
```
"""
function norm(itr, p::Real=2)
isempty(itr) && return float(norm(zero(eltype(itr))))
if p == 2
return norm2(itr)
elseif p == 1
return norm1(itr)
elseif p == Inf
return normInf(itr)
elseif p == 0
return typeof(float(norm(first(itr))))(count(!iszero, itr))
elseif p == -Inf
return normMinusInf(itr)
else
normp(itr, p)
end
end
"""
norm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
# Examples
```jldoctest
julia> norm(2, 1)
2.0
julia> norm(-2, 1)
2.0
julia> norm(2, 2)
2.0
julia> norm(-2, 2)
2.0
julia> norm(2, Inf)
2.0
julia> norm(-2, Inf)
2.0
```
"""
@inline function norm(x::Number, p::Real=2)
afx = abs(float(x))
if p == 0
if x == 0
return zero(afx)
elseif !isnan(x)
return oneunit(afx)
else
return afx
end
else
return afx
end
end
norm(::Missing, p::Real=2) = missing
# special cases of opnorm
function opnorm1(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m, n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for j = 1:n
nrmj::Tsum = 0
for i = 1:m
nrmj += norm(A[i,j])
end
nrm = max(nrm,nrmj)
end
end
return convert(Tnorm, nrm)
end
function opnorm2(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m,n = size(A)
if m == 1 || n == 1 return norm2(A) end
Tnorm = typeof(float(real(zero(T))))
(m == 0 || n == 0) ? zero(Tnorm) : convert(Tnorm, svdvals(A)[1])
end
function opnormInf(A::AbstractMatrix{T}) where T
require_one_based_indexing(A)
m,n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for i = 1:m
nrmi::Tsum = 0
for j = 1:n
nrmi += norm(A[i,j])
end
nrm = max(nrm,nrmi)
end
end
return convert(Tnorm, nrm)
end
"""
opnorm(A::AbstractMatrix, p::Real=2)
Compute the operator norm (or matrix norm) induced by the vector `p`-norm,
where valid values of `p` are `1`, `2`, or `Inf`. (Note that for sparse matrices,
`p=2` is currently not implemented.) Use [`norm`](@ref) to compute the Frobenius
norm.
When `p=1`, the operator norm is the maximum absolute column sum of `A`:
```math
\\|A\\|_1 = \\max_{1 ≤ j ≤ n} \\sum_{i=1}^m | a_{ij} |
```
with ``a_{ij}`` the entries of ``A``, and ``m`` and ``n`` its dimensions.
When `p=2`, the operator norm is the spectral norm, equal to the largest
singular value of `A`.
When `p=Inf`, the operator norm is the maximum absolute row sum of `A`:
```math
\\|A\\|_\\infty = \\max_{1 ≤ i ≤ m} \\sum _{j=1}^n | a_{ij} |
```
# Examples
```jldoctest
julia> A = [1 -2 -3; 2 3 -1]
2×3 Array{Int64,2}:
1 -2 -3
2 3 -1
julia> opnorm(A, Inf)
6.0
julia> opnorm(A, 1)
5.0
```
"""
function opnorm(A::AbstractMatrix, p::Real=2)
if p == 2
return opnorm2(A)
elseif p == 1
return opnorm1(A)
elseif p == Inf
return opnormInf(A)
else
throw(ArgumentError("invalid p-norm p=$p. Valid: 1, 2, Inf"))
end
end
"""
opnorm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
This is equivalent to [`norm`](@ref).
"""
@inline opnorm(x::Number, p::Real=2) = norm(x, p)
"""
opnorm(A::Adjoint{<:Any,<:AbstracVector}, q::Real=2)
opnorm(A::Transpose{<:Any,<:AbstracVector}, q::Real=2)
For Adjoint/Transpose-wrapped vectors, return the operator ``q``-norm of `A`, which is
equivalent to the `p`-norm with value `p = q/(q-1)`. They coincide at `p = q = 2`.
Use [`norm`](@ref) to compute the `p` norm of `A` as a vector.
The difference in norm between a vector space and its dual arises to preserve
the relationship between duality and the dot product, and the result is
consistent with the operator `p`-norm of a `1 × n` matrix.
# Examples
```jldoctest
julia> v = [1; im];
julia> vc = v';
julia> opnorm(vc, 1)
1.0
julia> norm(vc, 1)
2.0
julia> norm(v, 1)
2.0
julia> opnorm(vc, 2)
1.4142135623730951
julia> norm(vc, 2)
1.4142135623730951
julia> norm(v, 2)
1.4142135623730951
julia> opnorm(vc, Inf)
2.0
julia> norm(vc, Inf)
1.0
julia> norm(v, Inf)
1.0
```
"""
opnorm(v::TransposeAbsVec, q::Real) = q == Inf ? norm(v.parent, 1) : norm(v.parent, q/(q-1))
opnorm(v::AdjointAbsVec, q::Real) = q == Inf ? norm(conj(v.parent), 1) : norm(conj(v.parent), q/(q-1))
opnorm(v::AdjointAbsVec) = norm(conj(v.parent))
opnorm(v::TransposeAbsVec) = norm(v.parent)
norm(v::Union{TransposeAbsVec,AdjointAbsVec}, p::Real) = norm(v.parent, p)
"""
dot(x, y)
x ⋅ y
For any iterable containers `x` and `y` (including arrays of any dimension) of numbers (or
any element type for which `dot` is defined), compute the dot product (or inner product
or scalar product), i.e. the sum of `dot(x[i],y[i])`, as if they were vectors.
`x ⋅ y` (where `⋅` can be typed by tab-completing `\\cdot` in the REPL) is a synonym for
`dot(x, y)`.
# Examples
```jldoctest
julia> dot(1:5, 2:6)
70
julia> x = fill(2., (5,5));
julia> y = fill(3., (5,5));
julia> dot(x, y)
150.0
```
"""
function dot(x, y) # arbitrary iterables
ix = iterate(x)
iy = iterate(y)
if ix === nothing
if iy !== nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
return dot(zero(eltype(x)), zero(eltype(y)))
end
if iy === nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
(vx, xs) = ix
(vy, ys) = iy
s = dot(vx, vy)
while true
ix = iterate(x, xs)
iy = iterate(y, ys)
ix === nothing && break
iy === nothing && break
(vx, xs), (vy, ys) = ix, iy
s += dot(vx, vy)
end
if !(iy === nothing && ix === nothing)
throw(DimensionMismatch("x and y are of different lengths!"))
end
return s
end
dot(x::Number, y::Number) = conj(x) * y
"""
dot(x, y)
x ⋅ y
Compute the dot product between two vectors. For complex vectors, the first
vector is conjugated. When the vectors have equal lengths, calling `dot` is
semantically equivalent to `sum(dot(vx,vy) for (vx,vy) in zip(x, y))`.
# Examples
```jldoctest
julia> dot([1; 1], [2; 3])
5
julia> dot([im; im], [1; 1])
0 - 2im
```
"""
function dot(x::AbstractArray, y::AbstractArray)
lx = length(x)
if lx != length(y)
throw(DimensionMismatch("first array has length $(lx) which does not match the length of the second, $(length(y))."))
end
if lx == 0
return dot(zero(eltype(x)), zero(eltype(y)))
end
s = zero(dot(first(x), first(y)))
for (Ix, Iy) in zip(eachindex(x), eachindex(y))
@inbounds s += dot(x[Ix], y[Iy])
end
s
end
###########################################################################################
"""
rank(A::AbstractMatrix; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ)
rank(A::AbstractMatrix, rtol::Real)
Compute the rank of a matrix by counting how many singular
values of `A` have magnitude greater than `max(atol, rtol*σ₁)` where `σ₁` is
`A`'s largest singular value. `atol` and `rtol` are the absolute and relative
tolerances, respectively. The default relative tolerance is `n*ϵ`, where `n`
is the size of the smallest dimension of `A`, and `ϵ` is the [`eps`](@ref) of
the element type of `A`.
!!! compat "Julia 1.1"
The `atol` and `rtol` keyword arguments requires at least Julia 1.1.
In Julia 1.0 `rtol` is available as a positional argument, but this
will be deprecated in Julia 2.0.
# Examples
```jldoctest
julia> rank(Matrix(I, 3, 3))
3
julia> rank(diagm(0 => [1, 0, 2]))
2
julia> rank(diagm(0 => [1, 0.001, 2]), rtol=0.1)
2
julia> rank(diagm(0 => [1, 0.001, 2]), rtol=0.00001)
3
julia> rank(diagm(0 => [1, 0.001, 2]), atol=1.5)
1
```
"""
function rank(A::AbstractMatrix; atol::Real = 0.0, rtol::Real = (min(size(A)...)*eps(real(float(one(eltype(A))))))*iszero(atol))
isempty(A) && return 0 # 0-dimensional case
s = svdvals(A)
tol = max(atol, rtol*s[1])
count(x -> x > tol, s)
end
rank(x::Number) = x == 0 ? 0 : 1
"""
tr(M)
Matrix trace. Sums the diagonal elements of `M`.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> tr(A)
5
```
"""
function tr(A::AbstractMatrix)
checksquare(A)
sum(diag(A))
end
tr(x::Number) = x
#kron(a::AbstractVector, b::AbstractVector)
#kron(a::AbstractMatrix{T}, b::AbstractMatrix{S}) where {T,S}
#det(a::AbstractMatrix)
"""
inv(M)
Matrix inverse. Computes matrix `N` such that
`M * N = I`, where `I` is the identity matrix.
Computed by solving the left-division
`N = M \\ I`.
# Examples
```jldoctest
julia> M = [2 5; 1 3]
2×2 Array{Int64,2}:
2 5
1 3
julia> N = inv(M)
2×2 Array{Float64,2}:
3.0 -5.0
-1.0 2.0
julia> M*N == N*M == Matrix(I, 2, 2)
true
```
"""
function inv(A::AbstractMatrix{T}) where T
n = checksquare(A)
S = typeof(zero(T)/one(T)) # dimensionful
S0 = typeof(zero(T)/oneunit(T)) # dimensionless
dest = Matrix{S0}(I, n, n)
ldiv!(factorize(convert(AbstractMatrix{S}, A)), dest)
end
inv(A::Adjoint) = adjoint(inv(parent(A)))
inv(A::Transpose) = transpose(inv(parent(A)))
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T<:Real} = _vectorpinv(transpose, v, tol)
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T<:Complex} = _vectorpinv(adjoint, v, tol)
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T} = _vectorpinv(adjoint, v, tol)
function _vectorpinv(dualfn::Tf, v::AbstractVector{Tv}, tol) where {Tv,Tf}
res = dualfn(similar(v, typeof(zero(Tv) / (abs2(one(Tv)) + abs2(one(Tv))))))
den = sum(abs2, v)
# as tol is the threshold relative to the maximum singular value, for a vector with
# single singular value σ=√den, σ ≦ tol*σ is equivalent to den=0 ∨ tol≥1
if iszero(den) || tol >= one(tol)
fill!(res, zero(eltype(res)))
else
res .= dualfn(v) ./ den
end
return res
end
# this method is just an optimization: literal negative powers of A are
# already turned by literal_pow into powers of inv(A), but for A^-1 this
# would turn into inv(A)^1 = copy(inv(A)), which makes an extra copy.
@inline Base.literal_pow(::typeof(^), A::AbstractMatrix, ::Val{-1}) = inv(A)
"""
\\(A, B)
Matrix division using a polyalgorithm. For input matrices `A` and `B`, the result `X` is
such that `A*X == B` when `A` is square. The solver that is used depends upon the structure
of `A`. If `A` is upper or lower triangular (or diagonal), no factorization of `A` is
required and the system is solved with either forward or backward substitution.
For non-triangular square matrices, an LU factorization is used.
For rectangular `A` the result is the minimum-norm least squares solution computed by a
pivoted QR factorization of `A` and a rank estimate of `A` based on the R factor.
When `A` is sparse, a similar polyalgorithm is used. For indefinite matrices, the `LDLt`
factorization does not use pivoting during the numerical factorization and therefore the
procedure can fail even for invertible matrices.
# Examples
```jldoctest
julia> A = [1 0; 1 -2]; B = [32; -4];
julia> X = A \\ B
2-element Array{Float64,1}:
32.0
18.0
julia> A * X == B
true
```
"""
function (\)(A::AbstractMatrix, B::AbstractVecOrMat)
require_one_based_indexing(A, B)
m, n = size(A)
if m == n
if istril(A)
if istriu(A)
return Diagonal(A) \ B
else
return LowerTriangular(A) \ B
end
end
if istriu(A)
return UpperTriangular(A) \ B
end
return lu(A) \ B
end
return qr(A,Val(true)) \ B
end
(\)(a::AbstractVector, b::AbstractArray) = pinv(a) * b
function (/)(A::AbstractVecOrMat, B::AbstractVecOrMat)
size(A,2) != size(B,2) && throw(DimensionMismatch("Both inputs should have the same number of columns"))
return copy(adjoint(adjoint(B) \ adjoint(A)))
end
# \(A::StridedMatrix,x::Number) = inv(A)*x Should be added at some point when the old elementwise version has been deprecated long enough
# /(x::Number,A::StridedMatrix) = x*inv(A)
/(x::Number, v::AbstractVector) = x*pinv(v)
cond(x::Number) = x == 0 ? Inf : 1.0
cond(x::Number, p) = cond(x)
#Skeel condition numbers
condskeel(A::AbstractMatrix, p::Real=Inf) = opnorm(abs.(inv(A))*abs.(A), p)
"""
condskeel(M, [x, p::Real=Inf])
```math
\\kappa_S(M, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\right\\Vert_p \\\\
\\kappa_S(M, x, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\left\\vert x \\right\\vert \\right\\Vert_p
```
Skeel condition number ``\\kappa_S`` of the matrix `M`, optionally with respect to the
vector `x`, as computed using the operator `p`-norm. ``\\left\\vert M \\right\\vert``
denotes the matrix of (entry wise) absolute values of ``M``;